[英]How to change the value of another component property? (Angular 2)
I have a mane page that have a button that triggers a pop up box to appear: 我有一个鬃毛页面,其中包含一个按钮,该按钮会触发一个弹出框出现:
<i class="material-icons" (click)="openPopUp()">info</i>
openPopUp() is just setting the property to true: openPopUp()只是将属性设置为true:
openPopUp() {
this.showPopup = true;
}
and then im sending the value of showPopUp
to the PopupComponent(its separate component): 然后,我将
showPopUp
的值发送到PopupComponent(其单独的组件):
<div *ngIf="showPopup === true">
<pop-up-info-box [componentBPopUp]="showPopup"></pop-up-info-box>
</div>
but now in the componenetB i have the closePopUp func that is triggered from the html: 但是现在在componenetB中,我具有从html触发的closePopUp函数:
and is just setting the componentBPopUp to be false: 并且只是将componentBPopUp设置为false:
@Input public componentBPopUp: boolean; public closePopUp() { this.popUp = false; }
but what actually need to be set to false is the showPopup
in the first component...how do I set its value properly? 但是实际上需要设置为false的是第一个组件中的
showPopup
...如何正确设置其值?
thanks 谢谢
What you should do in ComponentB is to raise an event on close. 您在ComponentB中应该做的是在关闭时引发一个事件。
@Output() onClose: EventEmitter<boolean> = new EventEmitter();
public closePopUp() {
this.onClose.emit(true);
}
Now on the parent just subscribe to this event: 现在,父级只需订阅此事件:
<div *ngIf="showPopup === true">
<pop-up-info-box [componentBPopUp]="showPopup" (onClose)="showPopup = false">
</pop-up-info-box>
</div>
You should use @Output in componentBPopUp. 您应该在componentBPopUp中使用@Output。
for example: 例如:
close(){
this.showPopup = false;
}
Example of what you trying to do: 您尝试执行的操作示例:
https://plnkr.co/edit/kUWrlnoXgJ15rXObdaqh?p=preview https://plnkr.co/edit/kUWrlnoXgJ15rXObdaqh?p=preview
Good Luck!!! 祝好运!!!
To your question a parent component can refer to a child component using the @ViewChild
decorator 对于您的问题,父组件可以使用
@ViewChild
装饰器引用子组件。
@ViewChild('popup')
popup: ModalComponent;
this.popup.doStuff();
<div *ngIf="showPopup === true">
<pop-up-info-box #popup [componentBPopUp]="showPopup"></pop-up-info-box>
</div>
But your specific problem can be solved with two-way data binding between the componentBPopUp and the showPopup field (see here ) 但是您可以通过componentBPopUp和showPopup字段之间的双向数据绑定来解决您的特定问题(请参阅此处 )
Another option is to use EventEmmiter to notify the other component of the change (see here ) 另一个选择是使用EventEmmiter通知更改的其他组件(请参见此处 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.