如何使用set将数据从父级传递到子级时@input装饰器的问题?



>我正在尝试将数据从父组件共享到子组件,我能够使用 @input 将数据传递给子组件,但我希望每当父组件发生变化时子组件中的数据都同步,我试图使用 set() 方法,但我收到错误 "如果'app-chat'是一个Angular组件,并且它有'childMessage'输入,那么请验证它是否是这个模块的一部分。

这是我的应用程序.模块.ts片段

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { ReactiveFormsModule } from '@angular/forms'
import { FormsModule } from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavComponent } from './nav/nav.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { HomeComponent } from './home/home.component';
import { ChatComponent } from './chat/chat.component';
@NgModule({
declarations: [
AppComponent,
NavComponent,
AboutComponent,
ContactComponent,
HomeComponent,
ChatComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
ReactiveFormsModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

子组件-------

import { DataService } from './../data.service';
import { Component, OnInit, Input } from '@angular/core';
import { ChatObject } from '../chat-object'

@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss']
})
export class ChatComponent implements OnInit {
childVal: any;

@Input()
set name(childMessage: any) {
this.childVal = childMessage;
console.log("updated child" + this.childVal);
};
get name(): any {
return this.childVal;
}
}

父组件.ts------------

message: string;
chatClick(text){
console.log("inside parent" + text);
this.message = text;
}

父组件.html---------

<app-chat [childMessage]="message"></app-chat>

在运行上述代码时,我在浏览器中收到以下错误

无法绑定到"子消息",因为它不是 的已知属性 "应用聊天"。 1. 如果"应用聊天"是一个 Angular 组件,并且它有 "子消息"输入,然后验证它是否是此模块的一部分。 2. 如果"应用聊天"是 Web 组件,则添加 "CUSTOM_ELEMENTS_SCHEMA"到"@NgModule.schemas" 组件来禁止显示此消息。 3. 要允许任何属性,请将"NO_ERRORS_SCHEMA"添加到 此组件的"@NgModule.schemas"。("][子消息]="消息">

我想要的是每次调用chatClick()函数时,我都想要 子组件中的值在那一刻自动更新?

可能是这个?

@Input('childMessage')
set name(childMessage:any){
this.childVal=childMessage;
console.log("updated child"+this.childVal);
};

相关内容

最新更新