Alternative to use ng-init in angular2

你离开我真会死。 提交于 2019-12-12 04:37:04

问题


I'm trying to build an ionic2 application. I want to send notifications to users when ibeacon is detected. It worked with this code in angularjs. How can I do this with angular2 like the code below?

<div class="row"  ng-controller="Example1Controller" ng-init="add()">

回答1:


You should call it inside the ngOnInit

export class yourComponents implements OnInit {
ngOnInit() {
  this.add();
}
}



回答2:


<div class="row"  ng-controller="Example1Controller" ng-init="add()">

Basically in above code ng-controller define the controller part which is .ts file (constructor) for angular2 you can call any method or anything from there, also there is ngOnInit() life cycle hook present in angular2.

For more info see here also

Difference between Constructor and ngOnInit




回答3:


In Angular2, ng-init is used as a "lifecycle hook" that can be added to your components. Your components need to implement OnInit, and any initialization you need to perform can be executed inside of the ngOnInit method.

You can read more about Angular2 lifecycle hooks and view examples here: https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html




回答4:


Import OnInit directive and implement it in your component class. Then ngOnInit which is life cycle hook can be used. ngOnInit is invoked after constructor.

    import { Component, OnInit } from '@angular/core';

    @Component({    
    selector: 'app-my-component',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.css']
    })
    export class MyComponentComponent implements OnInit {
    constructor() { }
    ngOnInit() {
       //your code
     }
    }


来源:https://stackoverflow.com/questions/43051335/alternative-to-use-ng-init-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!