angular's ng-init alternative in Angular 2

后端 未结 8 881
遇见更好的自我
遇见更好的自我 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:48

    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 = new EventEmitter();
    
        ngOnInit() {
            this.ngInit.emit();
        }
    }
    

    And then use it like:

    ...

    Demo

提交回复
热议问题