[英]how can i call a function when a template loads in angular2?
我是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?请帮我解决这个问题。
@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
检查组件的生命周期事件https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html 。 根据你的说法你可能需要ngAfterViewInit
在angular2中,您可以使用组件阶段ngOnInit
它等于ngOnInit
中的on-init。 以下是有关角度生命周期的更多信息。
例:
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}`);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.