【问题标题】:angular2 change @input value in child component then change this value in parent component not workangular2 在子组件中更改@input 值,然后在父组件中更改此值不起作用
【发布时间】:2017-09-08 10:42:10
【问题描述】:

父组件类

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

为什么?

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

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

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

    这意味着你的 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---

    【讨论】:

    • 谢谢。你的回答更好。
    • @NieWei 别提了:)
    • 你忘了说如果不给子组件添加以下内容,双向绑定将不起作用:this.isShowChange.next(false);
    【解决方案2】:

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

    【讨论】:

    • 感谢您回答我的问题。
    【解决方案3】:

    您正在创建子级和父级之间不同步的值。由于父级将值向下传递给子级,因此您只需更改父级中的值。要将值从子级发送到父级,您需要使用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 方法运行时,这会发出值 false。父组件接收该新值并将其分配给它的 show 变量,该变量被发送到子组件。

    【讨论】:

    • 感谢您回答我的问题。
    猜你喜欢
    • 2019-07-28
    • 2016-11-23
    • 2021-06-26
    • 1970-01-01
    • 2019-08-27
    • 2021-11-27
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多