angular's ng-init alternative in Angular 2

后端 未结 8 836
遇见更好的自我
遇见更好的自我 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 13:02
    @Directive({
      selector: '[ngxInit]',
    })
    export class NgxInitDirective {
      constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef) {
      }
    
      @Input() set ngxInit(val: any) {
        this.viewContainer.clear();
        this.viewContainer.createEmbeddedView(this.templateRef, {ngxInit: val});
      }
    }
    

    a value expression is set via *ngxInit and published using as micro-syntax:

    <div *ngxInit="3 * i + j as idx">{{idx}}</div>
    

    published as https://www.npmjs.com/package/ngx-init

    0 讨论(0)
  • 2020-12-01 13:02

    It is possible by using OnInit Life Cycle hook as below,

    1. Import OnInit from core library

      import {Component, OnInit} from '@angular/core'
      
    2. Implement it to your component class

      export class App  implements OnInit {
      
      }
      
    3. Implement the ngOnInit method

       ngOnInit(){
          this.myText='Hello World!'
      
         }
      

    LIVE DEMO

    0 讨论(0)
提交回复
热议问题