我正在尝试使用另一组件的选择器将数据从一个组件发送到另一个组件,但无法发送显示以下错误的数据
NG8002:无法绑定到“myCounter”,因为它不是“app-child”的已知属性。
<h1>below code is from app.component.html</h1>
<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>
<h1>below code is from app.module.ts</h1>
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 { }
<h1>below code is from app.component.ts</h1>
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--;
}
}
<h1>below code is from child.component.ts</h1>
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
添加到 declarations
中的 AppModule
数组中。
@NgModule({
declarations: [AppComponent, ChildComponent], // <-- Add AppComponent
imports: [BrowserModule, AppRoutingModule],
providers: [provideClientHydration()],
bootstrap: [AppComponent],
})
export class AppModule {}