在组件之间调用函数

时间:2018-11-05 09:57:23

标签: angular6

我有两个组件(comp1和comp2)。我正在尝试从comp2调用comp1内部的函数,并且该函数没有发生,并且引发了错误。但是当从comp1调用comp2内部的函数时,它是成功的。

我希望它以两种方式发生 (即) (a)来自comp1内部的comp2的函数触发器 (b)comp2内部的comp1中的功能触发器

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

1 个答案:

答案 0 :(得分:0)

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

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

app.component.html

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

app.component.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