首页 > 解决方案 > 如何从另一个 [Angular] 调用一个组件的方法

问题描述

我是网络开发的新手。我正在做一个 Angular 项目。我有两个组件,filter-panelfilter-bar。他们都不是彼此的亲子关系。我检查了一些解决方案,例如:

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

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

我尝试了两种方法:

  1. @ViewChild

  2. 角度服务

    但我仍然遇到错误。

错误类型错误:“_co.filterPanel 未定义”

这是我的代码。

filter-bar.component.html

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

过滤条.component.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() {
    }
}

过滤器面板.component.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() {}
}

这里不涉及数据发送或接收。我只是想看看这个方法是如何被调用的,剩下的我来处理。我确定我在某个地方犯了一个可怕的错误。我也创建了一个堆栈闪电战。恐怕我混合了两种方法,让自己更加困惑。请纠正我。

标签: angulartypescript

解决方案


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

另一个解决方案但很丑陋是

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

推荐阅读