angular - 如何从另一个 [Angular] 调用一个组件的方法
问题描述
我是网络开发的新手。我正在做一个 Angular 项目。我有两个组件,filter-panel和filter-bar。他们都不是彼此的亲子关系。我检查了一些解决方案,例如:
以及互联网上的许多其他解决方案。
我尝试了两种方法:
@ViewChild
角度服务
但我仍然遇到错误。
错误类型错误:“_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() {}
}
这里不涉及数据发送或接收。我只是想看看这个方法是如何被调用的,剩下的我来处理。我确定我在某个地方犯了一个可怕的错误。我也创建了一个堆栈闪电战。恐怕我混合了两种方法,让自己更加困惑。请纠正我。
解决方案
如果您想使用@ViewChild访问它,您需要将FilterPanelComponent放在FilterBarComponent视图中。现在您在应用程序组件中同时使用它们,这就是您无法访问它的原因。如果你想在它们之间提供通信,我会建议你创建一个带有Subject的服务,其中一个会监听它,然后在预期的时候采取行动。
另一个解决方案但很丑陋是
- 访问AppComponent
@ViewChild(FilterPanelComponent, {static : false}) public filterPanel: FilterPanelComponent;
内部 - 单击按钮时从FilterBarComponent向AppComponent发出事件
- 在AppComponent中监听该事件并从FilterPanelComponent调用方法
推荐阅读
- javascript - 这段 javascript 代码在做什么?我正在研究使用这段代码的反应上下文 api。谁能解释一下?
- mysql - 基数是数据库约束吗?
- android - 有没有办法在 android 应用程序中注入 cookie/会话?
- javascript - 使用 setTimeout 将上下文转换为 redux
- java - 如何定义一个 Java 函数来接受一个函数
- c - C中的类似矩阵结构的邻接
- mysql - MySQL默认插入时间戳
- java - 执行存储过程不适用于 JdbcCursorItemReader
- mysql - 安装 MySQL 时指定的端口 3306 已被使用
- c# - 我的列表会话没有检索正确的值