简体   繁体   中英

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() {
    this.showPopup = true;
  }

and then im sending the value of showPopUp to the PopupComponent(its separate component):

<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:

close

and is just setting the componentBPopUp to be 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?

thanks

What you should do in ComponentB is to raise an event on close.

@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.

for example:

  close(){
    this.showPopup = false;
  }

Example of what you trying to do:

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('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 )

Another option is to use EventEmmiter to notify the other component of the change (see here )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM