ngOnChanges 在我的组件上根本没有触发

ngOnChanges not firing at all on my component

我正在尝试测试 ngOnchanges,所以我创建了一个新项目,这是我的 app.component.ts.html

app.component.ts:

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnChanges {

  @Input() mydata?: string;
  

  ngOnChanges(changes: SimpleChanges) {

    console.log(changes); // This does not appear in my console

  }

  change() {
    this.mydata = 'some change here';
  }

}

app.component.html

<h1>NG Changes</h1>

Changes: {{ mydata | json }}

<button (click)="change()">Change</button> 

为什么我没有从 ngOnchanges 得到任何结果...它似乎根本没有被触发。

我该如何解决这个问题?

ngOnChanges 仅当对 @Input 变量的引用由其 parent 组件调整时才会触发。目前你似乎没有任何 parent-child component relationship.

例如

子组件 (*.ts)

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `<h1>App child</h1>`
})
export class ChildComponent implements OnChanges {
  @Input() mydata?: string;

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
  }
}

父组件 (*.ts)

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  data: any;
}

父模板 (*.html)

<app-child [mydata]="data"></app-child>

<hr>
<input #myInput />
<button (mouseup)="data=myInput.value">Push value to data</button>

另请注意,ngOnChanges 仅在值更改时才会触发,因此在上例中尝试使用相同的值再次单击按钮不会触发它。

工作示例:Stackblitz