[英]angular2 change @input value in child component then change this value in parent component not work
parent component class 父组件类
export class Parent {
show: boolean = false;
constructor() { }
showChild() {
this.show = true;
}
}
parent component template 父组件模板
<child [isShow]="show"></child>
child component class 子组件类
export class Child {
@Input isShow: boolean = false;
constructor() { }
onClick() {
this.isShow = false;
}
}
after I triggered onClick() in child component, the showChild() would not work to show the child component. 在我触发子组件中的onClick()后,showChild()无法显示子组件。
why? 为什么?
The value is being passed exclusively from parent to child because you're using square brackets. 由于您使用的是方括号,因此该值仅从父级传递给子级。
In order for the value to go both ways, you need to use a two-way data binding. 为了使值双向,您需要使用双向数据绑定。
That means your isShow attribute should be like: 这意味着你的isShow属性应该是这样的:
@Input() isShow: boolean;
@Output() isShowChange = new EventEmitter<boolean>();
And the template should be 模板应该是
<child [(isShow)]="show"></child>
or 要么
<child [isShow]="show" (isShowChange)="show = $event"></child>
Take a look at the two-way data binding tutorial page: 看一下双向数据绑定教程页面:
https://angular.io/guide/template-syntax#two-way-binding--- https://angular.io/guide/template-syntax#two-way-binding---
You are creating values out of sync between the child and parent. 您正在创建子级和父级之间不同步的值。 Since the parent is passing the value down into the child, you need to change the value in the parent only. 由于父级将值传递给子级,因此您只需更改父级中的值。 To send a value from the child to the parent you need to use an Output
parameter as an EventEmitter
. 要将值从子节点发送到父节点,您需要使用Output
参数作为EventEmitter
。 It will look like this: 它看起来像这样:
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);
}
}
This emits the value false
when the onClick
method in the child runs. 当子onClick
中的onClick
方法运行时,这会发出false
值。 The parent receives that new value and assigns it to it's show
variable, which gets sent down to the child component. 父级接收该新值并将其分配给它的show
变量,该变量将被发送到子组件。
You need to use a getter
and setter
for the value so you can use the two-way data binding syntax. 您需要为值使用getter
和setter
,以便可以使用双向数据绑定语法。 This can be accomplished using the following: 这可以使用以下方法完成:
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.