我是angular2的新手。我需要在模板加载/初始化时调用函数。我知道如何在angular1.x中执行此操作,但我无法找到如何在angular-2中完成此操作。
<div ng-init="getItems()">
//some logic to get my items
</div>
getItems = function(){
console.log('in the getitems function call');
//logic to get my items from db/localStorage
}
这是我在angular1.x中使用ng-init的方法,但是angular-2中没有ng-init?请帮我解决这个问题。
答案 0 :(得分:2)
@Component({
...
})
class MyComponent {
constructor() {
// when component class instance is created
}
ngOnChanges(...) {
// when inputs are updated
}
ngOnInit() {
// after `ngOnChanges()` was called the first time
}
ngAfterViewInit() {
// after the view was created
}
ngAfterContentInit() {
// after content was projected
}
}
另请参阅https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#hooks-overview了解完整列表
答案 1 :(得分:1)
检查组件https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html的生命周期事件。根据你的说法你可能需要ngAfterViewInit
答案 2 :(得分:1)
在angular2中,您可以使用组件阶段ngOnInit
,它等于angularJS中的on-init。以下是有关lifecycle in angular的更多信息。
示例:
export class PeekABoo implements OnInit {
constructor(private logger: LoggerService) { }
// implement OnInit's `ngOnInit` method
ngOnInit() {
this.logIt(`OnInit`);
}
protected logIt(msg: string) {
this.logger.log(`#${nextId++} ${msg}`);
}
}