如何从另一个[Angular]调用一个组件的方法



我是web开发的新手。我正在做一个Angular项目。我有两个组件,过滤器面板过滤条。他们都不是父子关系。我检查了一些解决方案,比如:

从另一个访问一个组件的方法

以及互联网上的许多其他解决方案。

我尝试了两种方法:

  1. @ViewChild

  2. 角度中的服务

    但我还是犯了一个错误。

错误类型错误:&quot_co.filterPanel未定义";

这是我的代码。

filter-bar.component.html

<button (click)="filterPanel.filterPanelMethod()">Call</button>

过滤条组件.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FilterPanelComponent } from './filter-panel/filter-panel.component';
import { FilterPanelService } from './filter-panel/filter-panel.service';
@Component({
selector: 'app-filter-bar',
templateUrl: './filter-bar.component.html'
})
export class FilterBarComponent implements OnInit {
@ViewChild(FilterPanelComponent, {static : false}) public filterPanel: FilterPanelComponent;

constructor(public filterPanelService: FilterPanelService) {      
//filterPanelService.filterPanelMethod();
}
ngOnInit() {
}
}

过滤面板组件.ts

import { Component, OnInit } from '@angular/core';
import {FilterPanelService} from './filter-panel.service';
@Component({
selector: 'app-filter-panel',
templateUrl: './filter-panel.component.html'
})
export class FilterPanelComponent implements OnInit {
constructor(public filterPanelService:FilterPanelService) {
}
filterPanelMethod() {
console.log("I'm filter-panel method");
}
ngOnInit() {}
}

此处不涉及数据发送或接收。我只想看看这个方法是如何调用的,我会处理剩下的。我确信我在某个地方犯了一个严重的错误。我还创建了一个stackblitz。恐怕我混淆了两种方法,使自己更加困惑。请纠正我。

如果要使用@ViewChild访问FilterBarComponent视图,则需要将Filter PanelComponent放在该视图内。现在你在应用程序组件中同时使用了它们,这就是你无法访问它的原因。如果你想在它们之间提供通信,我建议你创建一个带有Subject的服务,其中一个将监听,然后在预期时采取行动。

另一个解决方案,但相当丑陋的是

  1. 访问AppComponent内部的@ViewChild(FilterPanelComponent, {static : false}) public filterPanel: FilterPanelComponent;
  2. 单击按钮时,从FilterBarComponentAppComponent发出事件
  3. AppComponent中侦听该事件,并从FilterPanelComponent调用方法

您需要进行以下两项更改:

  1. 从filter-bar.component.html 调用过滤器面板

    <app-filter-panel></app-filter-panel>
    
  2. 在filter-bar.component.ts中,您需要使用this访问服务引用。例如:

    this.filterPanelService.someMethod();
    

最新更新