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

时间:2017-04-12 14:58:22

标签: angular typescript

父组件类

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()无法显示子组件。

为什么?

3 个答案:

答案 0 :(得分:13)

由于您使用方括号,因此该值仅从父级传递给子级。

为了使值双向进行,您需要使用双向数据绑定。

这意味着你的isShow属性应该是:

$("#myTextArea").on("input", ...);

模板应该是

@Input()  isShow: boolean;
@Output() isShowChange = new EventEmitter<boolean>();

<child [(isShow)]="show"></child>

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

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

答案 1 :(得分:1)

您正在创建子级和父级之间不同步的值。由于父级将值传递给子级,因此您只需更改父级中的值。要将子项中的值发送给父级,您需要使用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);
    }
}

当子进程中的false方法运行时,会发出值onClick。父级接收该新值并将其分配给它的show变量,该变量将被发送到子组件。

答案 2 :(得分:1)

您需要使用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;
    }
}