Alternative to use ng-init in angular2

2019-08-25 07:17发布

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()">

4条回答
混吃等死
2楼-- · 2019-08-25 07:46

You should call it inside the ngOnInit

export class yourComponents implements OnInit {
ngOnInit() {
  this.add();
}
}
查看更多
Bombasti
3楼-- · 2019-08-25 07:47
<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

查看更多
放荡不羁爱自由
4楼-- · 2019-08-25 07:52

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
     }
    }
查看更多
Root(大扎)
5楼-- · 2019-08-25 07:58

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

查看更多
登录 后发表回答