我注意到如果我们根据函数声明[ngClass],应用程序会连续调用该函数。或者如果我们绑定到一个布尔变量,它也会在没有任何反应的情况下检查该值。
我想知道是否有办法让ngClass具有相同的效果,但只有在"事情发生时才调用该函数或检查布尔值"。按下按钮或按任意按钮。
我不知道解决方案是否可以使用ngChange但是我没有看到更改类的方法,而没有直接在控制器中引用DOM元素我试图逃避。
答案 0 :(得分:2)
你是完全正确的。任何 @Input()属性发生更改时,都会触发ngOnChanges()
生命周期挂钩。
例如,
在您的主要组件中
<app-child-component [childData]="childData"> Some Text </app-child-component>
this.service.getData().subscribe((data)=>{
this.childData = data;
});
当前childData值已更改
ngOnChanges(changes: SimpleChanges){
if(this.childData){
//when value is present
this.assignSomeClass();
}
}
assignSomeClass(){
///your code for ngClass
}
注意:ChildComponent必须有@Input() childData:any[]
答案 1 :(得分:0)
使用:host(..)和@HostBinding
考虑一下你有一个组件你想要根据某些设置应用不同的CSS类,比如.yellow-style,如果你指定和.red-style,当你传入红色时:。
这里要注意的重要一点是,与我们到目前为止所做的不同,我们不希望CSS类应用于组件内部的某个元素,而是应用于组件本身。例如:
<styled style="red" _nghost-c0="" ng-reflect-style="red" class="red-
style">
<div _ngcontent-c0="">
I'm a div that wants to be styled
</div>
</styled>
但是,为了可重用性,我们的样式应该与组件本身一起提供,所以我们再次使用StyledComponent的styles属性:
@Component({
selector: 'styled',
template: `
<div>
I'm a div that wants to be styled
</div>
`,
styles: [
`
:host(.yellow-style) {
background-color: yellow;
border: 1px solid black;
display:block;
}
:host(.red-style) {
background-color: red;
border: 1px solid black;
color: white;
display:block;
}
`
]
})
export class StyledComponent { }
如您所见,我们使用特殊的:host(...)选择器来定位承载组件的元素上的样式。有关此问题的官方文档的更多信息。通过这种方式,.yellow-style和.red-style将在主机组件级别可见,而它们将以其他方式封装,仅适用于StyledComponent中的元素。
接下来,我们定义一个@Input()属性,它允许我们传递样式配置。
@Component({...})
export class StyledComponent {
@Input() style;
}
我们仍然缺少的是根据样式输入属性的值以编程方式在主机元素上设置CSS类。我们使用@HostBinding:
import { Component, Input, HostBinding } from '@angular/core';
@Component({ ... })
export class StyledComponent {
@Input() style;
@HostBinding('class.yellow-style') yellowStyle:boolean = false;
@HostBinding('class.red-style') redStyle:boolean = false;
ngOnChanges(changes) {
let newStyle = changes.style.currentValue;
if(newStyle === 'yellow') {
this.yellowStyle = true;
this.redStyle = false;
} else if(newStyle === 'red') {
this.yellowStyle = false;
this.redStyle = true;
} else {
// nothing here.. (fallback?)
}
}
}
在ngOnChanges中,我们将样式输入属性更改,我们正确调整样式标志。 (注意到目前为止这不是最聪明的代码,但它很简单,所以你明白了:wink:)。
撰稿:https://juristr.com/blog/2016/01/learning-ng2-dynamic-styles/ 所有的优点。收集到了。你也有一个在网站上玩的例子。