[英]@input in different instances of same component angular problem
我有一個 angular 9 項目,在這個項目中有一個組件,它是一個名為 custom-select-option 的自定義 select 選項。 在這個組件中,我有一個@input,它是自定義 select 的選項。選擇時應從列表中隱藏 select。 當我將從 API 檢索到的相同數據提供給該組件的多個實例時,當我 select 一個選項時,它從兩個實例中隱藏,但它必須從單擊的實例中隱藏。
在自定義選擇選項組件中:
@Input() public data: customSelectOptionData[];
onOptionSelected(text: string | number, value: any): void {
this.isListOpen = false;
this.titleSpan.nativeElement.innerHTML = text;
if (this.controlName) this.inputHidden.nativeElement.value = value;
if (this.parentFormGroup && this.controlName)
this.parentFormGroup.get(this.controlName).setValue(value)
this.optionSelected.emit(String(value));
this.data.forEach(item => {
if (item.value === this.selectedOption.value) {
item.hide = false;
}
if (item.value === value) {
item.hide = true;
}
});
this.selectedOption.text = text;
this.selectedOption.value = value;
}
在應用程序組件中:
this.style.getAllStyles().pipe(take(1)).subscribe(data => {
this.mainInstrumentStyles = [...data];
this.secondInstrumentStyles = [...data];
});
在應用組件 html
<custom-select-option [data]="mainInstrumentStyles]></custom-selec-option>
<custom-select-option [data]="secondInstrumentsStyle]></custom-selec-option>
我怎樣才能防止這些實例對彼此的輸入數據產生影響?
很可能您正在將同一個 object 的引用發送到多個組件實例。 嘗試像下面這樣創建一個深拷貝
this.style.getAllStyles().pipe(take(1)).subscribe(data => {
this.mainInstrumentStyles = JSON.parse(JSON.stringify([...data]));
this.secondInstrumentStyles = JSON.parse(JSON.stringify([...data]));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.