角度自定义样式指令值在开头未定义



我有一个自定义指令,用于设置图标的颜色。

@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是未定义的。我在控制台中得到了一个错误(错误类型错误:ctx_r1.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>

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>

这样,只有当customStyle不是未定义的时,HTML才会呈现

值customStyle.color不可用,因为在初始化时customStyle本身是undefined。customStyle稍后在setTImeout解析时填充。

你能试试这个吗

<fa-icon [icon]="item.icon" [styledIcon]="customStyle?.color" size="2x"></fa-icon>

您可以为您的属性设置默认初始化"customStyle">

export class AppComponent implements OnInit {
customStyle: Style = {
///
color: 'ffffff'
}
...
}

在这种情况下,一旦setTimeOut完成,ngOnit将替换默认值。

我建议您从";this.elementService.getColor(("等待响应并填充您的customStyleProperty。因为,如果您的服务耗时超过5秒怎么办。

最新更新