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

标签 javascript angularjs angular

我是 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/

相关文章:

javascript - knockout foreach 子数组未显示

javascript - 删除多边形的顶点谷歌地图API v3

angular - Angular 分量的绝对或相对 "templateUrls"

angular - 如何限制素材输入中的特殊字符

JavaScript 开发 - 为代码行添加书签?

javascript - 数据在 Controller 中可用,但在 html 中无法解析

unit-testing - 单元测试时未在指令中调用 scope.$watch

angularjs 从 json 文件中获取 ng-repeat 数据非常慢

Angular 2 + ng 测试 : 'X' is not a known component

javascript - Highcharts - 如何并排显示 30 多个列