简体   繁体   中英

Passing boolean value is not getting shared from one component to another - Angular

This is just simple usecase, but don't get what I'm missing.

I've componentA & componentB. Passing booloan value via click event from componentB to componentA using eventEmitter , to show/hide particular div in componentA.

So far

componentB

public showLayOut = false;
@Output() passThisValue = new EventEmitter<boolean>();

ngOnInit(): void {
    this.showLayOut = false;
}

triggerEventToPassBoolVal() {

    this.someService(baseLink).subscribe((data) => {
        if (data[0].status === true) {
            this.showLayOut = true;
            if (this.showLayOut) {
                this.passThisValue.emit(this.showLayOut);
            }
        }
    })
}

componentA.html

<div *ngIf="showLayOut">
   <p>Show this div if emitted value is true, otherwise hide</p>
</div>

Could anyone pls help me to point out what i did wrong?, if possible pls share any existing stackblitz working sample

Note: im using form like this to submit data (ngSubmit)="OK(data)" Thanks

If componentA is parent component of componentB . I have that solution. for ex:

  import { Component, OnInit, ViewContainerRef } from '@angular/core';
  
  // componentB.compoent.ts

  getParentComponent() {
    return this.viewContainerRef['_data'].componentView.component.viewContainerRef['_view'].component;
  }
  
  changeBooleanvalueMethod () {
     this.getParentComponent().showLayOut = true; // showLayOut is componentA variable
  }

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