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

查看:265
本文介绍了仅当主机上存在特定类时,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');

推荐答案

使用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天全站免登陆