angular - 角度自定义样式指令值在开头未定义
问题描述
我有这个自定义指令,用于为图标设置颜色。
@Directive({
selector: '[styledIcon]'
})
export class StyledIconDirective implements OnInit {
constructor(private el: ElementRef) { }
@Input('styledIcon') color: string;
@HostListener('mouseenter') onMouseEnter() {
this.setHoverStyle();
}
@HostListener('mouseleave') onMouseLeave() {
this.setStyle();
}
setHoverStyle() {
this.el.nativeElement.style.color = 'green';
}
setStyle(){
this.el.nativeElement.style.color = this.color;
}
ngOnInit(){
this.setStyle();
}
}
当我在 html 中设置值时,这可以正常工作。问题是我通过服务加载了这种风格的颜色。在此之前可能还会调用其他几个服务。所以我用setTimeOut
下面的来演示这个场景。
export class AppComponent implements OnInit {
customStyle: Style;
constructor(private elementService: ElementServiceService){}
ngOnInit(): void {
setTimeout (() => {
this.customStyle= this.elementService.getColor();
}, 5000);
}
}
下面是使用该样式的 html。样式设置和图标颜色在 5 秒后更改。但在那之前 customStyle 是未定义的。我在控制台中遇到错误(ERROR TypeError: ctx_r1.customStyle is undefined)。有没有办法避免控制台错误。
<div *ngFor="let item of (menuItems$|async)" class="col-lg-3">
<fa-icon [icon]="item.icon" [styledIcon]="customStyle.color" size="2x"></fa-icon>
</div>
customStyle?.color
不起作用,因为它在 5 秒后没有设置样式
解决方案
仅当customStyle
不是未定义时才能显示图标
<div *ngFor="let item of (menuItems$|async)" class="col-lg-3">
<fa-icon *ngIf="customStyle" [icon]="item.icon" [styledIcon]="customStyle.color" size="2x"></fa-icon>
</div>
或者
<div *ngIf="customStyle">
<div *ngFor="let item of (menuItems$|async)" class="col-lg-3">
<fa-icon [icon]="item.icon" [styledIcon]="customStyle.color" size="2x"></fa-icon>
</div>
</div>
这样 HTML 只会在customStyle
未定义时呈现
推荐阅读
- vector - 向量投影的问题
- java - OpenLiberty Maven Plugin 无法将looseaplication 设置为 false
- docker - 为什么我无法从本地连接 redis cli?
- reactjs - NavLink 不添加 activeClassName (react-router-dom v5.2.0)
- firebase - 如何在 Stream Builder Flutter 上更改元素颜色
- python - 如果元素是元组,numpy 查找均值
- javascript - 如何根据属性过滤 JSON 数据?
- python-3.x - 尝试在python中反转字节数组(来自十六进制)
- assembly - 当两者都用于计算值时,LEA 或 MOV 有什么区别?
- r - R; plot basic:multicharts:在oma边界处绘制一个框