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

问题描述 投票:0回答:1

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

angular typescript angular7
1个回答
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();
 }
}

这是stackblitz的例子https://stackblitz.com/edit/hello-angular-6-tbufva

© www.soinside.com 2019 - 2024. All rights reserved.