我是 angular2 的新手。我需要在模板加载/初始化时调用一个函数。我知道如何在 angular1.x 中执行此操作,但我无法找出如何在 angular-2 中执行此操作。
这是我在 angular1.x 中尝试的方式
在 html 中
<div ng-init="getItems()">
//some logic to get my items
</div>
在 Controller 中
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完整列表
关于javascript - 在angular2中加载模板时如何调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39160564/