I want to run ngOnInit() of one component in another component without refreshing the current page.
            Asked
            
        
        
            Active
            
        
            Viewed 582 times
        
    0
            
            
        - 
                    1Refer this link https://stackoverflow.com/questions/37587732/how-to-call-another-components-function-in-angular2 – Sayan Apr 17 '19 at 07:04
- 
                    You have to define the second component as a **child** of the first – veben Apr 17 '19 at 07:19
- 
                    The parent component should do this. There are several ways to accomplish such, you may want to use `@ViewChild` to get a reference to the desired component, then use that reference to call `ngOnInit`. – briosheje Apr 17 '19 at 07:40
1 Answers
0
            
            
        Sample code for CompOneComponent
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-comp-one',
  templateUrl: './comp-one.component.html',
  styleUrls: ['./comp-one.component.css']
 })
export class CompOneComponent implements OnInit {
 constructor() { }
 ngOnInit() {
     console.log("CompOneComponent ngOnInit called successfully ..");
  }
 public compOneCall() {
    console.log("CompOneComponent called successfully ..");
  }
}
Sample code for parent/AppComponent
import { Component, OnInit } from '@angular/core';
import { CompOneComponent } from './comp-one/comp-one.component';
@Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css'],
 providers: [CompOneComponent],
})
export class AppComponent implements OnInit {
public name = 'Angular 6';
constructor(private compOne: CompOneComponent) { }
ngOnInit() {
 this.compOne.ngOnInit();
 this.compOne.compOneCall();
 }
}
Here is stackblitz example https://stackblitz.com/edit/hello-angular-6-tbufva,
 
    
    
        Sayan
        
- 481
- 5
- 12
- 
                    It's show an error in Angular 7. Uncaught ReferenceError: viewChild is not defined at organizer.component.ts:21 – Hasee Amarathunga Apr 17 '19 at 08:21
- 
                    
- 
                    I want to call method of SomeComponent in another Component.I follow some codes. But it's not work in angular 7 – Hasee Amarathunga Apr 17 '19 at 09:37
- 
                    @HaseeAmarathunga Exactly same thing implemented here https://stackblitz.com/edit/hello-angular-6-tbufva. I'm calling CompOneComponent method from AppComponent. – Sayan Apr 17 '19 at 09:41
- 
                    Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/191970/discussion-between-sayan-samanta-and-hasee-amarathunga). – Sayan Apr 17 '19 at 10:20
