簡體   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