子组件 html 文件
<div [ngClass]="wrp_cls"></div>
子组件 TS 文件
@Input() config: any = {};
wrp_cls: any = [];
this.wrp_cls =[this.config.wrp_cls,'class1']
父组件
<child-component [config]="config"></child-component>
当我尝试从父组件更新类时,子组件中的样式没有更新,
完整工作示例 堆栈闪电战链接
你的父母.html
<button (click)="send()">Change Color </button>
<app-child [config]="config"></app-child>
你的父母...
config;
send(){
this.config = true;
}
你的孩子.html...
<p [ngClass]=" {'config' : classConfig} ">
child works!
</p>
你的孩子...
classConfig;
@Input('config') set config(value){
this.classConfig = value;
}
尝试以下方法;
@Input() config: any = {};
wrp_cls: any = [];
ngOnChanges() {
this.wrp_cls =[this.config.wrp_cls,'class1']
}
每当 Angular 检测到组件(或指令(的输入属性更改时,都会调用其ngOnChanges()
方法。
将代码放在ngOnInit
生命周期方法上,将执行一次。
如果要将子模板值绑定到输入值,请使用默认更改检测,绑定到输入值本身。
<div [ngClass]="config.wrp_cls">child component html file</div>
*分叉了GaurangDhorda的堆栈闪电战示例,为您创建一个演示:
堆栈闪电战示例
这将不需要您更改额外的代码。