2017-04-12 25 views
3

父組件類angular2變化的子組件然後更改父組件,此值不工作

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()將無法顯示子組件。

爲什麼?

回答

4

由於您使用的是方括號,所以該值僅由父項傳遞給子項。

爲了讓數值變爲兩種方式,您需要使用雙向數據綁定。

這意味着您的isShow屬性應該是這樣的:

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

而且模板應該是

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

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

看看雙向數據綁定教程頁面: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#two-way

+1

謝謝。你的回答比較好。 – NieWei

+0

@NieWei別提了:) –

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變量,該變量被髮送到子組件。

+0

感謝您回答我的問題。 – NieWei

0

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

感謝您回答我的問題。 – NieWei

相關問題