我正在尝试在某些操作上执行从子组件到父组件的通信。为此,我使用EventEmitter
和Output
库。我会告诉你到目前为止我做了什么。
这是我的子组件文件sports-list.component.ts
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-sportslist',
templateUrl: './sportslist.component.html'
})
export class SportsListComponent {
@Output()
contentUpdated = new EventEmitter<string>();
ngOnInit() {
this.contentUpdated.emit('complete');
}
}
这是我的父组件文件top-navigation.component.ts
import { SportsListComponent } from '../../sportslist/sportslist.component';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
selector: 'app-ui-top-navigation',
templateUrl: './top-navigation.component.html',
styleUrls: ['./top-navigation.component.css']
})
export class TopNavigationComponent implements OnInit {
get_data(event) {
console.log('event trigger');
console.log(event);
}
}
我的top-navigation.component.html
<app-sportslist (contentUpdated)="get_data($event)">
</app-sportslist>
这是我的所有代码看起来,当我尝试构建此代码时,我在屏幕上出现以下错误 -
模板解析错误中的错误:'app-sportslist'不是已知元素:1。如果'app-sportslist'是Angular组件,则验证它是否是此模块的一部分。 2.如果'app-sportslist'是Web组件,则将'CUSTOM_ELEMENTS_SCHEMA'添加到此组件的'@ NgModule.schemas'以禁止显示此消息。 (”
[ERROR - >]“):ng:///var/www/html/budgetbet/BudgetBetWebSite/src/app/shared/top-navigation/top-navigation.component.html@419:0
我是新来的表达和棱角分明的,不理解它要求我修复的东西,你的建议可能会有很大的帮助。
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TopNavigationComponent } from './top-navigation/top-navigation.component';
import { RouterModule } from '@angular/router';
@NgModule({
declarations: [
TopNavigationComponent,
SportsListComponent
]
})
export class SharedModule {}
将子组件添加到模块中的声明
declarations: [
...,
SportsListComponent
],
这篇文章帮助我理解了Angular https://medium.com/@cyrilletuzi/understanding-angular-modules-ngmodule-and-their-scopes-81e4ed6f7407中组件的混乱导入
正如@Sachila所说,您必须在父组件模块中声明子组件。
如果它们位于不同的模块中,则导出子模块并将其导入父模块
如果它们在同一模块中,请确保已声明两个组件。也许这只是这个例子中的拼写错误,但看起来你的Shared.module.ts中缺少以下行
从../../sportslist/sportslist.component'导入{SportsListComponent};
但基本结构如下:
//...imports
@NgModule({
imports: [
//for modules
],
providers: [
//for services
],
declarations: [
//for components
],
exports: [/*elements to be shared with other modules*/],
entryComponents: [],
})
//...