Alternative to use ng-init in angular2

2019-08-25 07:46发布

问题:

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
     }
    }