首页 > 解决方案 > 角度自定义样式指令值在开头未定义

问题描述

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

@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 秒后没有设置样式

标签: angular

解决方案


仅当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未定义时呈现


推荐阅读