Angular Renderer2 setStyle 仅当主机上存在特定类时 [英] Angular Renderer2 setStyle only if specific class present on host

查看:23
本文介绍了Angular Renderer2 setStyle 仅当主机上存在特定类时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 (spinner) 指令,可以使用 @HostBinding 添加/删除一个类 (.spinner).它还在激活时添加/删除 img (spinner.gif).

I have a (spinner) directive that may add/remove a class (.spinner) using @HostBinding. It also adds/removes an img (spinner.gif) when activated.

如果 .spinner 存在于主机上,则应用 scss 文件中定义的一系列样式:

If .spinner is present on the host, a bunch of styles defined in the scss file are applied:

.spinning {
  position: relative;
 }

.spinning img {
  display: block;
  width: 24px;
  margin: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-right: -50%;
  transform: translate(-50%, -50%)
 }

我想在我的指令中将这些样式应用到主机上.仅当使用 Renderer2ElementRef 存在某个类时,是否可以在主机上应用样式?

I want to apply these styles on the host from within my directive. Is it possible to apply styles on the host only if a certain class is present using Renderer2 and ElementRef?

这显然不起作用:

this.renderer.setStyle(this.el.nativeElement, '.spinning position', 'relative');

推荐答案

使用 can ElementRef 检查元素中是否存在类

Use can ElementRef to check whether the class present in the element or not

ngOnInit(){
  let present = this.ele.nativeElement.classList.contains('open');
  if(present){
  //Then add your style
   this.renderer2.setStyle(this.el.nativeElement,'color','red');  

  }
  }

示例:https://stackblitz.com/edit/angular-renderer2-dispatch-event-f4j56o

这篇关于Angular Renderer2 setStyle 仅当主机上存在特定类时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆