在组件之间调用函数



我有两个组件(comp1和comp2(。我试图从comp2调用comp1内部的一个函数,但它没有发生,并且抛出了一个错误。但是当从comp1调用comp2内部的函数时,它是成功的。

我希望这两种方式都能实现(即((a( 来自comp1内部comp2的函数触发器(b( comp2 内来自comp1的功能触发器

我已经附上了示例代码。https://stackblitz.com/edit/angular-jxfzqb

错误是从comp1上的构造函数抛出,它无法生成comp2的新实例。

请尽量不要在组件之间使用组件的提供,我建议您将组件从app.component绑定到comp1和comp2,例如:

app.component.html

<app-comp1 #comp1 [Comp2Component]="comp2"></app-comp1>
<app-comp2 #comp2 [Comp1Component]="comp1"></app-comp2>

应用程序组件.ts

import { Component, ViewChild } from '@angular/core';
import { Comp1Component } from './comp1/comp1.component';
import { Comp2Component } from './comp1/comp2/comp2.component';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';
// Get component with attr #comp1
@ViewChild('comp1') comp1: Comp1Component;
// Get component with attr #comp2
@ViewChild('comp2') comp2: Comp2Component;
}

comp1.component.ts

import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-comp1',
templateUrl: './comp1.component.html',
styleUrls: ['./comp1.component.css']
})
export class Comp1Component implements OnInit {
@Input() Comp2Component: Comp2Component;
constructor() { }
ngOnInit() {
}
funcInComp1() {
console.log("comp1 function triggered from comp2");
}
triggerComp2Function() {
this.Comp2Component.funcInComp2();
}
}

comp2.component.ts

import { Input, Component, OnInit } from '@angular/core';
import { Comp1Component } from '../comp1.component';
@Component({
selector: 'app-comp2',
templateUrl: './comp2.component.html',
styleUrls: ['./comp2.component.css']
})
export class Comp2Component implements OnInit {
@Input() Comp1Component: Comp1Component
constructor() { }
ngOnInit() {
}
triggerComp1Function() {
this.Comp1Component.funcInComp1();
}
funcInComp2() {
console.log("comp2 function triggered from comp1");
}
}

stackblitz:https://stackblitz.com/edit/angular-itmzhe

最新更新