简体   繁体   English

如何在angular2中加载模板时调用函数?

[英]how can i call a function when a template loads in angular2?

I am new to angular2. 我是angular2的新手。 I have a requirement to call a function when a template loads/initializes. 我需要在模板加载/初始化时调用函数。 I know how to do this in angular1.x., but I am not able to find out how it can be done in angular-2. 我知道如何在angular1.x中执行此操作,但我无法找到如何在angular-2中完成它。

This is how I tried in angular1.x 这是我在angular1.x中尝试的方式

In html 在HTML中

<div ng-init="getItems()">
//some logic to get my items
</div>

In controller 在控制器中

getItems = function(){
console.log('in the getitems function call');
//logic to get my items from db/localStorage
} 

This is how I used ng-init in angular1.x, but there is no ng-init in angular-2?Please help me on this issue. 这是我在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
  }
}

See also https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#hooks-overview for the full list 有关完整列表,另请参阅https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#hooks-overview

Check lifecycle events of a component https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html . 检查组件的生命周期事件https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html From what you are saying you probably needs ngAfterViewInit 根据你的说法你可能需要ngAfterViewInit

In angular2 you can use component phase ngOnInit it is equal to on-init in angularJS. 在angular2中,您可以使用组件阶段ngOnInit它等于ngOnInit中的on-init。 Here is more information about lifecycle in angular . 以下是有关角度生命周期的更多信息。

Example: 例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM