0

I have a question, I hope you can guide me, I am working in an angular application with Firestore and I need to call the ngOnInit method of a component from another component, the problem with this is that both components are integrated in different parts. The first is a header that is inside a component that contains more headers, this uses a component that contains a Router-Outlet, which is where I need to call the ngOnInit method of the Header.

This is the ngOnInit method of the app-header-user that I want to call

Component({
  selector: 'app-header-user',
  templateUrl: './app-header-user.component.html',
  styleUrls: ['./app-header-user.component.scss']
})

export class HeaderUserComponent implements OnInit{
 ngOnInit() {
   Some code...
  }
}

The first component (header) is contained like this along with other headers in app-header:

<ul>
  <li><app-header-notify></app-header-notify></li>
  <li><app-header-user></app-header-user></li>
</ul>

This component that contains the headers is contained in a component together with a Router-Outlet.

 <app-header></app-header>
 <div class="inner-content">
    <router-outlet></router-outlet>
  </div>

I need to call the ngOnInit method of the app-header-user from a component contained in the Router-Outlet

I appreciate your attention and I hope you can help me.

  • You shouldn't be calling ngOnInit at all, Angular does this for you at the appropriate time. – wlf Jun 18 '20 at 22:45
  • What's in your ngOnInit? – wlf Jun 18 '20 at 22:46
  • You should move the code in your ngOnInit to another function that you can call in that components ngOninit, then you can make your newlty made function public/shared and can share it to other components – ploofah Jun 18 '20 at 22:49
  • In my ngOnInit a query to Firestore is executed and it returns data that I require in my header, the problem is that I execute an insert to Firestore in a component of the Router-Outlet and I need to make the query again to update the header data – José de Jesús Sánchez Arellano Jun 18 '20 at 22:52
  • If you have everything wired up properly with the Firestore observables the header should auto update to reflect the modified database. Posting your header code and template would be useful to see if anything is wrong. – wlf Jun 18 '20 at 22:55
  • 1
    Thank you very much, I moved my code to a service and I handled it with observables, I thank you very much. – José de Jesús Sánchez Arellano Jun 19 '20 at 21:47

0 Answers0