如何简洁地在Angular renderer2中删除和添加类 [英] How to remove and add class in Angular renderer2 succinctly

查看:512
本文介绍了如何简洁地在Angular renderer2中删除和添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在两行中简洁地从元素中添加和删除类,而不用编写一堆if else语句

Is it possible to add and remove a class from your element succinctly, in two line instead of writing a whole bunch of if else statement

您可以这样做吗? 虽然不适合我

Can you do this? Not working for me though

for brevity
 constructor(private renderer: Renderer2,private elRef: ElementRef) {}
    const action = isDisabled ? 'addClass' : 'removedClass';
    this.renderer[action](div, 'disabled');

代替

if (isDisabled) {
        this.renderer.addClass(div, 'disabled');
    } else {
      this.renderer.removeClass(div, 'disabled');
    }

推荐答案

可以做到

const action = isDisabled ? 'addClass' : 'removeClass';
this.renderer[action](div, 'disabled');

甚至

this.renderer[isDisabled ? 'addClass' : 'removeClass'](div, 'disabled');

这是 removeClass ,而不是 remove d Class .这正是为什么不应该这样做的原因.

It is removeClass, not removedClass. And this is exactly the reason why this shouldn't be done.

括号表示法会禁用类型检查,因此可以访问不存在的属性而不会触发类型错误.

Bracket notation disables type checking, so it becomes possible to access non-existing properties without triggering type errors.

另一个原因是该代码可能更难阅读.

Another reason is that the code may be harder to read.

这篇关于如何简洁地在Angular renderer2中删除和添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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