Search code examples
angularlifecycle-hook

Trigger one component method after other component fully load


I have two components, both are loading in my <app-root> like this:

<app-header [calendarReference]="calendarRef"></app-header>

<app-calendar #calendarRef></app-calendar>

and index.html

<body>
  <app-root></app-root>
</body>

Is there a way to trigger <app-header> component method after <app-calendar> component is fully load?


Solution

  • Use @Output decorator. I don't know about your code, so I will assume the components:

    In your CalendarComponent:

    import { Component, AfterViewInit } from '@angular/core';
    import { Output, EventEmitter } from '@angular/core';
    
    @Component({
      ...
    })
    export class CalendarComponent implements AfterViewInit {
        @Output() calendarLoaded: EventEmitter<boolean> = new EventEmitter();
    
        ngAfterViewInit(){
            console.log('Calendar Loaded');
            this.calendarLoaded.emit(true);
        }
    }
    

    Catch the event in you app.component.html:

    <app-header #appHeader></app-header>
    
    <app-calendar #calendarRef (calendarLoaded)="afterCalendarLoaded()"></app-calendar> 
    

    .. and this is how your app.component.ts would look:

    import {Component,ViewChild} from '@angular/core';
    import {HeaderComponent} from './header.component';
    
    @Component({
      ...
    })
    export class AppComponent {
        @ViewChild('appHeader') appHeader: HeaderComponent;
    
        afterCalendarLoaded(){
            this.appHeader.someMethod();
        }    
    }
    

    Here is a working plunker demo. See the console log.