简体   繁体   中英

In Angular 7 run method of another Component without refreshing current page?

我想在另一个组件中运行一个组件的ngOnInit()而不刷新当前页面。

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 ,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM