angular's ng-init alternative in Angular 2

后端 未结 8 882
遇见更好的自我
遇见更好的自我 2020-12-01 12:14

What is the alternative of ng-init=\"myText=\'Hello World!\'\" in Angular 2 to add in the template, not in the component

 
8条回答
  •  被撕碎了的回忆
    2020-12-01 12:37

    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

    or to make values available

    • 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

提交回复
热议问题