我试图将数据从父组件共享到子组件,我能够使用@input将数据传递到子组件,但是我希望子组件中的数据在发生变化时保持同步父组件,我正在尝试使用set()方法,但由于出现错误 “如果'app-chat'是Angular组件,并且具有'childMessage'输入,则请验证它是否是此模块的一部分。”
这是我的app.module.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;
}
}
父component.ts ------------
message: string;
chatClick(text){
console.log("inside parent" + text);
this.message = text;
}
parent component.html ---------
<app-chat [childMessage]="message"></app-chat>
运行上面的代码时,我在浏览器中收到以下错误
无法绑定到“ childMessage”,因为它不是的已知属性 “应用聊天”。 1.如果“ app-chat”是Angular组件,并且具有 输入“ childMessage”,然后验证它是否属于此模块。 2.如果“ app-chat”是一个Web组件,则添加 “ CUSTOM_ELEMENTS_SCHEMA”到此的“ @ NgModule.schemas” 组件以禁止显示此消息。 3.要允许任何属性,请将“ NO_ERRORS_SCHEMA”添加到 该组件的“ @ NgModule.schemas”。 (“] [childMessage] =” message“>
我想要的是每次调用chatClick()
函数时我想要
子组件中的值要在那一刻自动更新?
答案 0 :(得分:2)
这可能吗?
@Input('childMessage')
set name(childMessage:any){
this.childVal=childMessage;
console.log("updated child"+this.childVal);
};