Search code examples
angularparent-childweb-component

How to access a web component located inside a child component


The parent component include this on its template:

<six-drawer label="Notificaciones" class="notifications">
 <mur-notification-dialog (newEmision)="listenNewEmision($event)"></mur-notification-dialog>
 <six-button slot="footer" class="open-all-notifications-button" (click)="openNotifications()">
  Ver todas las notificaciones
 </six-button>
</six-drawer>

From parent component I need to check if six-drawer property open is true or not.


Solution

  • You could use a local reference to six-drawer in the template HTML and handle the open property like the following:

    @Component({...})
    export class SixDrawerComponent {
       open = false;
       isValid!: boolean;
    
       makeItValid(): void {
          this.isValid = true;
       }
    }
    
    <six-drawer #sixDrawer label="Notificaciones" class="notifications">
      ...
      <p>is six drawer open? {{ sixDrawer.open }}</p>
      <p>is six drawer valid? {{ sixDrawer.isValid }}</p>
    
      <button (click)="sixDrawer.makeItValid()">Make it valid</button>
    </six-drawer>
    

    Also, you could use ViewChild in order to handle the child programmatically like the following:

    <six-drawer #sixDrawer label="Notificaciones" class="notifications">
    </six-drawer>
    
    @Component({...})
    export class ParentComponent {
      @ViewChild('sixDrawer') sixDrawer!: SixDrawerComponent;
    
      someEvent(): void {
        const isOpen = this.sixDrawer.open; 
        // and then access the rest of the child component
      }
    }