[英]angular2 change @input value in child component then change this value in parent component not work
父組件類
export class Parent {
show: boolean = false;
constructor() { }
showChild() {
this.show = true;
}
}
父組件模板
<child [isShow]="show"></child>
子組件類
export class Child {
@Input isShow: boolean = false;
constructor() { }
onClick() {
this.isShow = false;
}
}
在我觸發子組件中的onClick()后,showChild()無法顯示子組件。
為什么?
由於您使用的是方括號,因此該值僅從父級傳遞給子級。
為了使值雙向,您需要使用雙向數據綁定。
這意味着你的isShow屬性應該是這樣的:
@Input() isShow: boolean;
@Output() isShowChange = new EventEmitter<boolean>();
模板應該是
<child [(isShow)]="show"></child>
要么
<child [isShow]="show" (isShowChange)="show = $event"></child>
看一下雙向數據綁定教程頁面:
您正在創建子級和父級之間不同步的值。 由於父級將值傳遞給子級,因此您只需更改父級中的值。 要將值從子節點發送到父節點,您需要使用Output
參數作為EventEmitter
。 它看起來像這樣:
export class Parent {
show: boolean = false;
constructor() { }
showChild() {
this.show = true;
}
}
<child [isShow]="show" (updateValue)="show = $event"></child>
export class Child {
@Input isShow: boolean = false;
@Output() updateValue = new EventEmitter();
constructor() { }
onClick() {
this.updateValue.emit(false);
}
}
當子onClick
中的onClick
方法運行時,這會發出false
值。 父級接收該新值並將其分配給它的show
變量,該變量將被發送到子組件。
您需要為值使用getter
和setter
,以便可以使用雙向數據綁定語法。 這可以使用以下方法完成:
export class Child {
private isShowValue = false;
@Input()
public get isShow(){
return this.isShowValue;
}
@Output() isShowChange = new EventEmitter();
set isShow(val) {
this.isShowValue = val;
this.isShowChange.emit(this.isShowValue);
}
constructor() { }
onClick() {
this.isShow = false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.