What is the alternative of ng-init=\"myText=\'Hello World!\'\" in Angular 2 to add in the template, not in the component
A possible improvement over Günter's answer:
@Directive({
selector: 'ngInit',
exportAs: 'ngInit'
})
export class NgInit {
@Input() ngInit: () => any;
ngOnInit() {
if(typeof this.ngInit === 'function') {
this.ngInit();
} else {
// preventing re-evaluation (described below)
throw 'something';
}
}
}
And then use higher-order functions for passing in data, like so:
// component.ts
myInitFunction(info) {
// returns another function
return () => console.log(info);
}
If you use a higher-order function like this, you also don't need to worry about what this is inside of myInitFunction since an arrow function is really what is passed.
Use the directive like so:
// component.html
If you were to try and create a directive that doesn't pass in a function as the input in the manner described here, you run the risk of infinite loops. For example, you'd get that if you whole directive was simply evaluating the expression you gave it.
This is what would happen if your myInitFunction method didn't return another function (and your HTML was the same as above). You'd console out, return undefined, and then change detection would re-evaluate it, consoling out over and over.