我想在另一个组件中运行一个组件的ngOnInit()而不刷新当前页面。
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 ..");
}
}
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();
}
}
这是stackblitz的例子https://stackblitz.com/edit/hello-angular-6-tbufva,