Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular's ng-init alternative in Angular 2

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

like image 353
Shamil Avatar asked Jan 26 '17 04:01

Shamil


People also ask

What is Ng on init in angular?

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.

When Ng-INIT is called?

Answer: ng-init is called whenever the template is re-rendered.

How do you use ngOnInit?

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.


2 Answers

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 use
  • ngInit.values.a reads the a value from the created reference.

See also Converting Angular 1 to Angular 2 ngInit function

like image 169
Günter Zöchbauer Avatar answered Oct 04 '22 11:10

Günter Zöchbauer


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

like image 35
Augusto Barreto Avatar answered Oct 04 '22 12:10

Augusto Barreto