我正在為下拉串列制作自定義組件。我有一個正在初始化的配置物件,我ngOnInit()將用戶提供的默認配置和配置組合在一起@Input(),但是在父組件的運行時,如果我對配置物件進行任何更改,它不會更新ngOnChanges()我孩子的方法。
我試過這個:
子組件
@Input() config: MyConfig;
@Input() disabled: boolean
ngOnChanges() {
console.log('config', this.config); // this is not
console.log('disabled', this.disabled); // this is detecting
}
父組件html
<button (click)="changeConfig()">Change Config</button>
<app-child [config]="customConfig" [disabled]="newDisabled"></app-child>
父組件 ts
newDisabled = false;
customConfig = {
value: 'code',
label: 'name',
floatLabel: 'Select'
};
changeConfig() {
this.customConfig.value = 'name';
this.newDisabled = true;
}
對于 disbale 變數它正在作業,但對于配置它不是,我做錯了什么嗎?請幫忙
uj5u.com熱心網友回復:
您的問題是您ngOnInit正在將config變數設定為新物件。由于@Input()呼叫了一次,這會破壞您對原始物件的參考,并且不會檢測到更改。
您可以使用 setter 和 getter 解決此問題。我添加了一個堆疊閃電戰來演示這個波紋管。
塊參考
父組件
import { ChangeDetectorRef, Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
newDisabled = false;
customConfig = {
value: 'code',
label: 'name',
floatLabel: 'Select',
};
changeConfig1() {
this.customConfig.value = 'name1';
this.newDisabled = true;
console.log('Change Config 1');
}
changeConfig2() {
this.customConfig.value = 'name2';
this.newDisabled = true;
console.log('Change Config 2');
}
}
子組件
import { Component, Input } from '@angular/core';
class MyConfig {}
@Component({
selector: 'hello',
template: `<h1> config: {{config | json}}</h1><h1> disabled: {{disabled}}</h1>`,
styles: [],
})
export class HelloComponent {
private _defaultConfig = {
key: 'default',
};
@Input() disabled: boolean;
private _config: MyConfig;
@Input() config: MyConfig;
set () {
if (!this.config) {
this.config = new MyConfig(); // it is a class
} else {
this._config = {
...this.config,
...this._defaultConfig,
};
}
}
get () {
return this._config;
}
ngOnChanges() {
console.log('config', this.config);
console.log('config', this._config);
console.log('disabled', this.disabled);
}
}
uj5u.com熱心網友回復:
問題是只有在物件customConfig發生更改時才會觸發更改檢測。在您的示例中,僅value更新屬性。您可以執行以下操作parent.component.ts:
changeConfig() {
this.customConfig = Object.assign(this.customConfig, { value: 'name'});
this.newDisabled = true;
}
這將創建一個新的配置物件,其中包含更新的value屬性和舊的所有其他舊屬性customConfig。
uj5u.com熱心網友回復:
輸入物件通過參考進行比較,因此如果您想反映子組件和觸發器中的更改,請ngOnChanges執行以下操作:
changeConfig() {
this.customConfig = {...this.customConfig, value: 'name'};;
this.newDisabled = true;
}
并將您的以下代碼從 移動ngOnInit到ngOnChanges,可能在初始化時輸入 chagnes 可能不可用。
if (!this.config) {
this.config = new MyConfig(); // it is a class
} else {
this.config = {
...this._defaultConfig,
...this.config
};
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/342748.html
標籤:javascript 有角的 打字稿
