2017-03-31 59 views
0

在我的计划组成部分,我有以下指令,其中selectedPerson是服务的对象和的ShowModal是在规划组件本地布尔参数:Angular2布尔输入参数不工作

<person-popup [person]="planningService.selectedPerson" [show]="showModal"></person-popup> 

的PersonPopop组件具有以下简单结构:

import { Component, Input } from '@angular/core'; 
import { Counselor } from '../entities/counselor'; 
import { Person } from '../entities/person'; 
import { Request } from '../entities/request'; 


@Component({ 
    selector: 'person-popup', 
    templateUrl: './person-popup.component.html', 
    styleUrls: ['./person-popup.component.css'] 
}) 


export class PersonPopupComponent { 

    @Input() person: Person; 
    @Input() show: boolean; 

    constructor() { } 

    public displayCss() { 
     return this.show ? "displayBlock" : ""; 
    } 

    public toggleShow() { 
     this.show = !this.show; 
     console.log("toggleShow: ", this.show) 
    } 
} 

相应的HTML视图目前看起来像这样:

<p>{{show}}</p> 
<p>{{person?.name}}</p> 
<button (click)="toggleShow()">Show</button> 

<div class="modal-background {{displayCss()}}" (click)="toggleShow()"> 
    <div class="modal-content animate"> 
     {{person?.name}} 
    </div> 
</div> 

当Planning组件启动时,show属性为null。 selectedPerson的更改始终传播到弹出组件,但showModal参数的值不同。

showModal第一次设置为true在父级中时,它在子组件中设置为true

子组件将然后将其本地show属性设置为false。 之后,似乎“输入连接丢失”,并且showModal的所有后续更改不会传播到show

有关如何重新设计的建议?

+0

从子[更新父组件属性的可能重复组件在Angular 2](http://stackoverflow.com/questions/41464871/update-parent-component-property-from-child-component-in-angular-2) – n00dl3

回答

2

您需要使用双向绑定,如果你想更改传播从孩子到家长:

export class PersonPopupComponent { 

    @Input() person: Person; 
    @Input() show: boolean; 
    @Ouput() showChange= new EventEmitter<boolean>(); 

    constructor() { } 

    public displayCss() { 
     return this.show ? "displayBlock" : ""; 
    } 

    public toggleShow() { 
     this.show = !this.show; 
     this.showChange.emit(this.show); 
     console.log("toggleShow: ", this.show) 
    } 
} 
在父母

则:

<person-popup [person]="planningService.selectedPerson" [(show)]="showModal"></person-popup> 
+0

感谢您的快速回答!一些跟进问题,以确保我明白:1)你的意思是我需要做的就是在指令绑定中添加paranthesis,并添加相应的输出参数与发射器? 2)showChange命名约定会自动匹配双向绑定吗? 3)发出一个值并设置本地参数不是很混淆吗?只是调用this.showChange.emit(!this.show)并让它传播更改为Input参数是不够的吗? –

+1

1.是的。 2.'Change'后缀是用[[(bananaInABox)]'符号表示的,例如,可以命名为'showFoo',并使用'[show] =“someData”(showFoo)=“doSomething($ event )“'注意你可以用'(showChange)=”doSomething($ event)“来做同样的事情,盒子里的香蕉不是强制性的3.是的,我想这是可能的。 – n00dl3

+0

对于将来的读者,我只需添加对使用get/set方法执行双向绑定的另一篇文章的引用。这使得它更加冗长,但对于一些更复杂的情况可能会有用。 http://stackoverflow.com/a/39943368/1122813 –