Search code examples
angularangular-materialangular-componentsngoninit

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


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.


Solution

  • 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);
    }