英文:
ngclass not updating when updating from another component
问题
child component html 文件
<div [ngClass]="wrp_cls"></div>
child component ts 文件
@Input() config: any = {};
wrp_cls: any = [];
this.wrp_cls = [this.config.wrp_cls, 'class1'];
parent component
<child-component [config]="config"></child-component>
当我尝试从父组件更新一个类时,子组件中的样式未被更新。
英文:
child component html file
<div [ngClass]="wrp_cls"></div>
child component ts file
@Input() config: any = {};
wrp_cls: any = [];
this.wrp_cls =[this.config.wrp_cls,'class1']
parent component
<child-component [config]="config"></child-component>
when I try to update a class from from parent component , the style is not being updated in child component ,
答案1
得分: 3
完整的工作示例 StackBlitz 链接
您的 parent.html
<button (click)="send()">改变颜色</button>
<app-child [config]="config"></app-child>
您的 parent.ts
config;
send(){
this.config = true;
}
您的 Child.html
<p [ngClass]="{'config': classConfig}">
子组件工作中!
</p>
您的 Child.ts
classConfig;
@Input('config') set config(value){
this.classConfig = value;
}
英文:
Complete Working example StackBlitz Link
Your parent.html
<button (click)="send()">Change Color </button>
<app-child [config]="config"></app-child>
Your parent.ts...
config;
send(){
this.config = true;
}
Your Child.html...
<p [ngClass]=" {'config' : classConfig} ">
child works!
</p>
Your Child.ts...
classConfig;
@Input('config') set config(value){
this.classConfig = value;
}
答案2
得分: 1
尝试以下方法:
@Input() config: any = {}; wrp_cls: any = [];
ngOnChanges() { this.wrp_cls = [this.config.wrp_cls, 'class1'] }
Angular 在检测到组件(或指令)的输入属性发生变化时会调用其 ngOnChanges()
方法。
英文:
Try the below method;
@Input() config: any = {};
wrp_cls: any = [];
ngOnChanges() {
this.wrp_cls =[this.config.wrp_cls,'class1']
}
Angular calls its ngOnChanges()
method whenever it detects changes to input properties of the component (or directive).
答案3
得分: 0
将代码放在ngOnInit
生命周期方法中,将在执行一次。
如果您希望将子模板的值绑定到输入值,并使用默认的变更检测,请绑定到输入值本身。
<div [ngClass]="config.wrp_cls">子组件HTML文件</div>
*分叉自GaurangDhorda的stackblitz示例,为您创建了一个演示:
这不需要您额外更改任何代码。
英文:
Placing code on the ngOnInit
life cycle method, will execute it once.
if you wish to bind the child template value to the input value, using the default change detection, bind to the input value itself.
<div [ngClass]="config.wrp_cls">child component html file</div>
*forked GaurangDhorda's stackblitz example to create you a demo:
This will require no additional code changing on your part.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论