【发布时间】:2020-03-13 07:38:56
【问题描述】:
我是网络开发的新手。我正在做一个 Angular 项目。我有两个组件,filter-panel 和 filter-bar。他们都不是彼此的亲子关系。我检查了一些解决方案,例如:
Access a method of one component from another
以及互联网上的许多其他解决方案。
我尝试了两种方法:
-
@ViewChild
-
角度服务
但我仍然遇到错误。
ERROR TypeError: "_co.filterPanel is undefined"
这是我的代码。
filter-bar.component.html
<button (click)="filterPanel.filterPanelMethod()">Call</button>
filter-bar.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() {
}
}
filter-panel.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() {}
}
这里不涉及数据发送或接收。我只是想看看这个方法是如何被调用的,剩下的我来处理。我确定我在某个地方犯了一个可怕的错误。我还创建了一个stackblitz。恐怕我混合了两种方法,让自己更加困惑。请纠正我。
【问题讨论】:
标签: angular typescript