Angular 2 expression parser and ng-init directive

后端 未结 2 1120
没有蜡笔的小新
没有蜡笔的小新 2021-01-17 11:01

Basically I\'m looking for a way to implement a counterpart to Angular 1.x ngInit directive.

I\'m aware of ngOnInit hook and the fact that

相关标签:
2条回答
  • 2021-01-17 11:17

    This can be achieved with a directive:

    @Directive({ selector: '[initialize]' })
    class InitializeDirective {
      @Output() initialize = new BehaviorSubject();
    }
    

    The expected use is:

    <div (initialize)="initViaMethodCall(); foo = 'init via assignment'"></div>
    <ng-template (initialize)="bar = 'init with no extra markup'"></template>
    {{ foo }}
    {{ bar }}
    
    0 讨论(0)
  • 2021-01-17 11:35

    Just a Workaround ( Plunker Demo ), see estus's answer for a solution

    init Directive:

    @Directive({
      selector: '[init]',
      inputs: ['init']
    })
    export class InitDir {
      init;
    
      ngOnChanges() {     // `ngOnInit` if you want it to run just once
        if(this.init){
          let iife = function(str){ return eval(str); }.call(this.init[0], this.init[1]);
        }
      }
    }
    

    Usage:

    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2 [init]="[this, 'this.name = 1; this.bar();']">Hello {{name}}</h2>
        </div>
      `,
    })
    export class App {
      constructor() {
        this.name = 'Angular2 (Release Candidate!)'
      }
    
      bar() {
        alert('Yo Bar!');
      }
    }
    
    0 讨论(0)
提交回复
热议问题