无法将数据从父组件发送到子组件,显示子组件是未知元素

问题描述 投票:0回答:1

我正在尝试使用另一组件的选择器将数据从一个组件发送到另一个组件,但无法发送显示以下错误的数据

NG8002:无法绑定到“myCounter”,因为它不是“app-child”的已知属性。

  1. 如果“app-child”是 Angular 组件并且具有“myCounter”输入,则验证它是否是该模块的一部分。
  2. 如果“app-child”是 Web 组件,则将“CUSTOM_ELEMENTS_SCHEMA”添加到该组件的“@NgModule.schemas”以抑制此消息。
  3. 要允许任何属性,请将“NO_ERRORS_SCHEMA”添加到该组件的“@NgModule.schemas”。
<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')
  }

}

angular angularjs
1个回答
0
投票

您需要将

AppComponent
添加到
declarations
中的
AppModule
数组中。

@NgModule({
  declarations: [AppComponent, ChildComponent], // <-- Add AppComponent
  imports: [BrowserModule, AppRoutingModule],
  providers: [provideClientHydration()],
  bootstrap: [AppComponent],
})
export class AppModule {}

演示@StackBlitz

© www.soinside.com 2019 - 2024. All rights reserved.