首页 > 解决方案 > 我的代码中没有触发 Angular 生命周期更改事件

问题描述

我创建了一个用于测试目的的组件来检查ngOnChanges()火灾与否。当我了解到这ngOnChanges()是在执行后触发的启动事件Constructor(),但在我的应用程序中它不起作用。

我的 TS 代码

constructor() { 
    console.log("constructor");
  }
  ngOnChanges(){ console.log("ngOnChanges"); }

  ngOnInit(){
    console.log("ngOnInit");
  }
  ngOnDestroy(){
    console.log("ngOnDestroy");
  }
  ngDoCheck(){
    console.log("ngDoCheck");
  }
  ngAfterContentInit(){ console.log("ngAfterContentInit"); }
  ngAfterContentChecked(){ console.log("ngAfterContentChecked"); }
  ngAfterViewInit(){ console.log("ngAfterViewInit"); }
  ngAfterViewChecked(){ console.log("ngAfterViewChecked"); }

HTML 页面代码

<h2>Test My Angular Life Cycle</h2>
<input type="buttton" value=""/>

标签: angular

解决方案


仅当组件具有绑定输入并且一个或多个数据绑定输入属性发生更改时,ngOnChanges 才会在 ngOnInit() 之前调用。如果你的组件没有输入或者你在没有提供任何输入的情况下使用它,框架将不会调用 ngOnChanges()。


推荐阅读