angular’s ng-init alternative in Angular 2

You can use a 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>
  • 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

Leave a Comment