Angular父子组件传值失败:NG8002错误排查求助
Angular父组件向子组件传值失败(NG8002错误)解决
错误信息
NG8002: Can't bind to 'myCounter' since it isn't a known property of 'app-child'.
- If 'app-child' is an Angular component and it has 'myCounter' input, then verify that it is part of this module.
- If 'app-child' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.
- To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.
相关代码
app.component.html
<div style="text-align:center"> <h1> My App </h1> <div> <button (click)="increment()">Addition</button> <button (click)="decrement()">Substract</button> <app-child [myCounter]="counter"></app-child> </div> </div>
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule, provideClientHydration } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { ChildComponent } from './component/child/child.component'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ ChildComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ provideClientHydration() ], bootstrap:[ AppComponent ] }) export class AppModule { }
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrl: './app.component.css', }) export class AppComponent { title = 'PracticeThiryOctober'; number:number=234232; get counter() { return this.number; } set counter(value) { this.number=value; } increment() { this.counter++; } decrement() { this.counter--; } }
child.component.ts
import { Component, OnInit,Input,OnChanges} from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrl: './child.component.css' }) export class ChildComponent implements OnChanges { @Input() myCounter!:number; ngOnChanges() { console.log('ngOnChanges') } }
问题根源
核心问题是**AppComponent未在AppModule的declarations数组中声明**。Angular要求所有在模块中使用的组件(包括根组件)必须加入declarations,否则Angular无法编译组件模板,进而无法识别模板中的app-child组件及其输入属性myCounter,最终触发NG8002错误。
修复方案
修改app.module.ts,将AppComponent添加到declarations数组:
import { NgModule } from '@angular/core'; import { BrowserModule, provideClientHydration } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { ChildComponent } from './component/child/child.component'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, // 新增这一行 ChildComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [ provideClientHydration() ], bootstrap:[ AppComponent ] }) export class AppModule { }
修复后,Angular能正确识别AppComponent及其模板内容,myCounter的属性绑定即可正常工作。
可选优化:在child.component.html中添加展示代码,确认传值结果:
<p>当前计数:{{ myCounter }}</p>
内容的提问来源于stack exchange,提问作者Decoder
相关产品推荐
相关产品推荐

