How to call ngOnit function of a component from another component in Angular

1.7k Views Asked by At

I have a component called "CreateBugsViewComponent" in this component I wat to use ngOnit function of my another component which is "ProjectBugsComponent" how can I do this the code for "CreateBugsViewComponent" is written below:

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { MatSnackBar } from '@angular/material/snack-bar';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { environment } from '../../environments/environment';

@Component({
  selector: 'app-createbugview',
  templateUrl: './createbugview.component.html',
  styleUrls: ['./createbugview.component.scss']
})
export class CreatebugviewComponent implements OnInit {
    onbugsubmit(){
    if(this.createbugform.valid)
    {
      this.createbugform.controls['BugsAttachments'].setValue(this.images);
      this.http.post(this.baseURI+'Bugs/Addbug',this.createbugform.value).subscribe(
        (data:any) => {
          this.dialogRef.close();
          //this.changeLocation(),
          this.snackbar.open(data.message,'✖', {
            duration:4000,
            horizontalPosition:'center',
            verticalPosition:'top'
          }),
          //this.dialog.closeAll(),
          localStorage.removeItem('ProjectId')/////////////////In this function I want to use ngOnit of  ProjectBugsComponent Component.
        }
      )
    }
  }

If there is any other information anyone wants then let me know in the comments I will provide you.

3

There are 3 best solutions below

1
On BEST ANSWER

Put the shared logic in a service and inject the service in the components.

Shared service

@Injectable({
  providedIn: 'root',
})
export class SharedLogicService {
  sharedFunction(router): void {
    console.log(router.routerState.snapshot.url, 'called')
  }
}

ComponentA or ComponentB

constructor(private router: Router, private sharedLogicService: SharedLogicService){}

ngOnInit() {
  this.sharedLogicService.sharedFunction(this.router);
}
0
On

Well, what you ask is actually a bad practice.
And the shortest solution with that bad practice would be:

  1. Create a static public method in ProjectBugsComponent (let's say we call it uglyMethod())
  2. Move out the logic of ngOnInit of ProjectBugsComponent to uglyMethod()
  3. From CreateBugsViewComponent import the ProjectBugsComponent and call ProjectBugsComponent.uglyMethod()

This would solve the problem, but again, what you ask is a bad practice.
In general, the best practice would be creating a service, moving out that common logic from ngOnInit to there, and calling it from both components whenever needed.

2
On

It's better to follow this article to approach the communication between the components. Angular already has the described approaches and this one is not in the list. But if you really want, here is an example:

app-layout.component.ts

import { StudentsComponent } from './../students/students.component';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, } from '@angular/router';

@Component({
  selector: 'app-layout',
  templateUrl: './app-layout.component.html',
  styleUrls: ['./app-layout.component.scss']
})
export class AppLayoutComponent implements OnInit {

  constructor(private route: ActivatedRoute, private studentsC: StudentsComponent) {

  }

  ngOnInit(): void {
    // calling NgOnInit in StudentComponent
    this.studentsC.ngOnInit()
  }

}

students.component.ts

import { Component, Injectable, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-students',
  templateUrl: './students.component.html',
  styleUrls: ['./students.component.scss']
})
//**!!! important to add**
@Injectable({
  providedIn: 'root',
})
export class StudentsComponent implements OnInit {

  constructor(private router: Router) { }
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;
  ngOnInit(): void {
    console.log(this.router.routerState.snapshot.url, 'called')
  }

}