What is the alternative of ng-init="myText='Hello World!'"
in Angular 2 to add in the template, not in the component
<div ng-app="" ng-init="myText='Hello World!'">
the alternative in Angular 2
The ng-init Directive is used to initialize AngularJS Application data. It defines the initial value for an AngularJS application and assigns values to the variables. The ng-init directive defines initial values and variables for an AngularJS application.
Answer: ng-init is called whenever the template is re-rendered.
Use ngOnInit() whenever you want to execute code when the component is FIRST initialized. Remember that ngOnInit() only fires once after data-bound properties are set. This means ngOnInit() will execute if you refresh your browser or first initialize a component but not when other events occur.
You can use a directive
@Directive({ selector: 'ngInit', exportAs: 'ngInit' }) export class NgInit { @Input() values: any = {}; @Input() ngInit; ngOnInit() { if(this.ngInit) { this.ngInit(); } } }
you can use it to pass a function to be called like
<div [ngInit]="doSomething"
or to make values available
<div ngInit [values]="{a: 'a', b: 'b'}" #ngInit="ngInit"> <button (click)="clickHandler(ngInit.values.a)">click me</button> </div>
ngInit
addes the directive[values]="{a: 'a', b: 'b'}"
sets some initial values#ngInit="ngInit"
creates a reference for later usengInit.values.a
reads the a
value from the created reference.See also Converting Angular 1 to Angular 2 ngInit function
Another approach is by using the @Output decorator and EventEmitter:
import {Directive, OnInit, Output, EventEmitter} from '@angular/core'; @Directive({ selector: '[ngInit]' }) export class NgInitDirective implements OnInit { @Output() ngInit: EventEmitter<any> = new EventEmitter(); ngOnInit() { this.ngInit.emit(); } }
And then use it like:
<div *ngIf="condition" (ngInit)="initialize()"> ... </div>
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With