我正在嘗試測驗,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';
}
}
應用程式組件.html
<h1>NG Changes</h1>
Changes: {{ mydata | json }}
<button (click)="change()">Change</button>
為什么我沒有從 ngOnchanges 得到任何結果......它似乎根本沒有被解雇。
我怎樣才能解決這個問題?
uj5u.com熱心網友回復:
ngOnChanges僅在其父組件@Input調整對變數的參考時才會觸發。目前您似乎沒有任何父子組件關系。
例如。
子組件 (*.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
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/332659.html
上一篇:每次更改輸入后如何不創建流?
下一篇:無法在瀏覽器上執行PUT方法
