在另一个组件的Angular 7中运行方法而不刷新当前页面吗?

时间:2019-04-17 06:56:39

标签: angular typescript angular7

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

1 个答案:

答案 0 :(得分:0)

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

这是https://stackblitz.com/edit/hello-angular-6-tbufva,{p>