2017-04-12 53 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

相关问题