Webpack throwing TypeError: Data must be a string or a buffer in Angular CLI

Recently I got some error unexpectedly while running my Angular-CLI application.

By default you will not get any information about the error which WebPack is throwing. But I will tell you , how you can log the exact error related to your issue. The reason could be different for your scenario.

Navigate to yoursource\node_modules\webpack\lib\dependencies and open HarmonyExportImportedSpecifierDependency.js file and log the import dependency
updateHash(hash) {
super.updateHash(hash);
const hashValue = this.getHashValue(this.importDependency.module);
if (this.importDependency.module != null){
// console.log('Module resource: ', this.importDependency.module.resource);
}else{
console.log('\nFile not found: ', this.importDependency);
}
hash.update(hashValue);
}

In my case I got the module in my application where the issue is.

Hope this helps

Template Variable to Interact with Child Components in Angular 2+

I have already discussed in my last couple of blogs to interact Components using @Input and @Output. Here I am going to explain about Template Variable to interact with Child Components. By using this Template reference variable you can access public properties and methods of a child component and also to bind data to a child component.
Template Reference Variable allow you to specify a variable name on a component and you can access any public property or methods on that component using that variable.

In order to demonstrate I have a product card component which is my child component placed inside the  ProductListComponent(parent component) to list some products. You can see I have added a template reference variable named #productReference on this child component

So over here in our ProductCardComponent will just a create a method and property to access from the ProductListComponent

Now you can access this property and method from the ProductListComponent

Load Components Dynamically at runtime in Angular 4

Angular Version I have used – 4.2.0
Here I am going to explain how to load dynamic components at runtime. By using angular ComponentFactoryResolver you can load components dynamically. In the below example I am loading a component dynamically in to another component at runtime .

DynamicComponentHostDirective
In order to load a dynamic component you have to create a directive that you can apply to ng-template , which will helps to place the components at run time. This directive injects ViewContainerRef to gain access to the view container of the element that will host the dynamically added component.
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[dynamiccomponent-host]',
})
export class DynamicComponentHostDirective {
constructor(public viewContainerRef: ViewContainerRef) {
}
}

ContainerComponent

This is just a place holder component to load the dynamic component.This component accepts an input(contains what component you want to load at runtime)  which is coming from a parent components or you can load from your service based on your implementation. This component is doing the major role to resolve the components at runtime. In this method you can also see a method named renderComponent() which ultimately loads the component name from a service and resolve with ComponentFactoryResolver and finally setting data to pass the dynamic component.
import { Component, Input, OnInit, AfterViewInit, ViewChild, ComponentFactoryResolver, OnDestroy } from '@angular/core';
import { DynamicComponentHostDirective } from './DynamicComponentHost.Directive;
import { YourInputDataModel } from './Data.Model';
import { DynamicComponentService } from "./DynamicComponent.Service";
@Component({
selector: 'container-component,
templateUrl: 'app/tile/ContainerComponent.Template.html'
})
export class ContainerComponent implements OnInit {
@Input() tile: any;
@ViewChild(DynamicComponentHostDirective ) componentHost: DynamicComponentHostDirective ;
constructor(private _componentFactoryResolver: ComponentFactoryResolver,private dynamicComponentService :DynamicComponentService ) {
}
ngOnInit() {

}
ngAfterViewInit() {
this.renderComponents();
}
renderComponents() {
let component=this.dynamicComponentService .getComponent(this.tile.componentName);
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(component);
let viewContainerRef = this.componentHost.viewContainerRef;
let componentRef = viewContainerRef.createComponent(componentFactory);
(componentRef.instance).data = this.tile;
}
}
export interface YourInputDataModel {
data: any;
}

You can see I have applied the directive we have created before to the ng-template

ContainerComponent.Template.html



DynamicComponentService
This is a simple angular service factory to register the component you want to load at runtime.

@Injectable()
//register your component
export class DynamicComponentService {
getComponent(componentName:string) {
if(componentName==="YourDynamicComponent"){
return YourDynamicComponent
}
else if(componentName==="OtherComponent"){
return OtherComponent
}
}
}

YourDynamicComponent(Component we registered inside the factory loads dynamically )
import { Component, OnInit, Input, ReflectiveInjector, Injector } from '@angular/core';
@Component({
selector: 'mydynamiccomponent',
templateUrl: 'app/templates/YourDynamicComponent.html'
})
export class YourDynamicComponent implements OnInit {
@Input() data: any;
constructor() {
}
ngOnInit() {

}
}

Entry Component

Finally to ensure that the compiler still generates a factory, add dynamically loaded components to the NgModule’s entryComponents array. You can add this in to your app module

@NgModule({
imports: [BrowserModule,HttpModule],
providers: [DynamicComponentService],
declarations: [

YourDynamicComponent,
OtherComponent
],
exports: [],
entryComponents: [YourDynamicComponent,OtherComponent],
bootstrap: [MainApplicationComponent]
})
export class AppModule {
constructor() {

}
}

Source Code
Download Source

Communicating with parent component from child component in Angular 2+

In my last blog I have explained about @Input decorator to pass data from parent component to the child component. @Output is on other hand used in response to some event within a child component to receive some information for the parent component through some events. If you are not read my previous blog , I would suggest you to read the same. I have used the same example here also.

Child Component
Let’s talk about the child component first. You can see I have a simple method named productCardClick() which I am calling when clicking on the button. It’s pretty straight forward.

Modifying the child component
Next I am going to pass some data to the parent through the same productCardClick() method in the child component. In order to do that first you have to add a new property of type EventEmitter and emit the data you want to pass in to the parent component through this property like below .

Parent Component
Let’s go the parent component named ProductListComponent


In the parent component (ProductListComponent) you can see I have receiver method named onProductCardClickHandled(data:any) with a parameter to receive the data from the child component and I am calling this receiver method with a parameter via the @Output decorated property onProductCardClick inside the child component. Now when you click the button you will receive the child component data in to the parent component

Communicating with child components from parent component in Angular 2+

Breaking our application in to multiple components makes our application more organized and maintainable. Here I am going to explain how to pass data from parent component to child component.

Parent Component
Here is our ProductListComponent , which is the parent component with a productObject declared which I am going to pass in to the child component.

This is my productList html for displaying the product object. You can see I am calling the product-card component(Child Component) from this productListComponent

Child Component

Child Component template

In this component I have declared a variable named product decorated with @Input , which tell to the child component that , you will get an input product from the parent component(ProductListComponent). For passing the input data from the parent component to the child component you have to add an attribute match with property decorated with the @Input inside a square bracket like below and the value here I am passing will be the productObject from the ProductListComponent

defineProperty method in Javascript

defineProperty is a method on Object which allow you to configure the properties to meet some criterias.
Here is a simple example with an employee object with two properties firstName & lastName and append the two properties by overriding the toString method on the object.
You will get Output as : Jameel Moideen

I am going to change the same code by using defineProperty on the object

The first parameter is the name of the object and then second parameter is name of the property we are adding , in our case it’s toString and then the last parameter is json object which have a value going to be a function and three parameters writable,enumerable and configurable.Right now I just declared everything as true.

If u run the example you will get Output as : Jameel Moideen

Let’s understand why we need the three properties such as writable,enumerable and configurable.
writable
One of the very annoying part of the javascript is , if you change the toString property to something else for example

if run this again , everything gets breaks
Let’s change writable to false. If run the same again you will get the correct output as ‘Jameel Moideen’ . This property will prevent overwrite this property later.
enumerable
if you print all the keys inside the object , you can see all the properties including toString.
console.log(Object.keys(employee));
if you set enumerable to false , you can hide toString property from everybody else. If run this again you will get firstName,lastName
configurable

if someone later redefined the object on later for example enumerable to true and run it. You can see toString property came again.


we no need this behavior , so you can restrict this by set configurable to false.

Set HTTP Cache Expiration in Angular JS and Typescript

Create an Interceptor for every service calls

angular.module('app').factory("cacheInterceptor", ["$cacheFactory", function ($cacheFactory) {
 var httpTtlCache = {};
 return {
 request: function (config) {
 var expirationTime;
 if (config.expiration) {
 expirationTime = config.expiration;
 delete config.expiration;
 if (new Date().getTime() - (httpTtlCache[config.url] || 0) > expirationTime) {
 $cacheFactory.get("$http").remove(config.url);
 httpTtlCache[config.url] = new Date().getTime();
 }
 }
 return config;
 }
 };
}]);

Push the interceptor through config

angular.module('app', []).config(['$httpProvider', function ($httpProvider) {
 $httpProvider.interceptors.push('cacheInterceptor');
}]);

Pass the expiration when you call your httpservice

  var expirationTime = 60 * 60 * 1000;
            $http.get(url, { expiration: expirationTime,cache:true }).then(function (response) {
               
            });