Search code examples
angularoutputangular6behaviorsubject

How child component could control visibility of itself in the parent on child component initialization?


There are two interchangeable child components in the parent, which visibility is governed by the parent variable showList

<div id="parent">
   <app-child-1 *ngIf="showList"></app-child-1>
   <app-child-2 *ngIf="!showList"></app-child-2>
</div>

How could I control the parent variable "showList" from the child component on its initialization?

I've tried to change it with Output and BehaviorSubject, but both this options doesn't work on initialization.


Solution

  • It looks like showList is a property of the parent component. This means that the parent component can set its value. You want the child components to "tell" the parent component that they wish to be displayed? If so you must declare an event on the child component and listen to it with your parent component. I am guessing that there will be a control on the child component which causes the view to switch, so basically the child component requests to be hidden not shown.

    EDIT: Since you want the child components to decide at run time which one of them is the one to display, you can't have them be hidden by *ngIf because then if they are hidden they are not even instantiated, and they cannot run any code which causes them to reappear. In this case you need to have them all present, but hidden from view using CSS.

    The event in the child component can be declared like this:

    @Output() hideMe = new EventEmitter<any>();
    

    And the listening at the parent component is done like this:

    <app-child-1 [class.hidden]="!showList" (hideMe)="showList=false"></app-child-1>
    <app-child-2 [class.hidden]="showList" (hideMe)="showList=true"></app-child-2>
    

    And the accompanying CSS:

    .hidden { display: none; }
    

    Then in your child component logic, when it's time to emit the event you should do:

    this.hideMe.emit();