繁体   English   中英

angular2更改子组件中的@input值然后更改父组件中的此值不起作用

[英]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>

看一下双向数据绑定教程页面:

https://angular.io/guide/template-syntax#two-way-binding---

您正在创建子级和父级之间不同步的值。 由于父级将值传递给子级,因此您只需更改父级中的值。 要将值从子节点发送到父节点,您需要使用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变量,该变量将被发送到子组件。

您需要为值使用gettersetter ,以便可以使用双向数据绑定语法。 这可以使用以下方法完成:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM