繁体   English   中英

将 HTML class 设置为在 Angular 指令中托管

[英]Set an HTML class to host in an Angular directive

您将如何使用 Angular 指令添加和设置可以通过参数更改的 HTML class? 假设我们有一个已经存在 class 的 div,但没有指令:

<div class="myClass"></div>

现在,我们要为其附加一个指令和一个参数:

<div directiveName set="X" class="myClass myClass-X"></div>

如果我需要 4,那么我动态添加的 class 将像这样更改:

<div directiveName set="4" class="myClass myClass-4"></div>

我完全知道如何使用@hostbinding 添加一个 class,但我找不到如何使用我的“设置”参数动态更改这个

非常感谢

如果我正确理解了您的问题,则可以按如下方式完成:

我是从 memory 做的,也许有些东西没有按预期工作,但我想你明白了。

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[directiveName]'
})
export class HighlightDirective {
    constructor(el: ElementRef) {
       
       // Check if element has the 'set' directive.
       if('set' in el.nativeElement.attributes){
         // Get the "set" attribute.
         const setAttribute = el.nativeElement.getAttribute('set');

         // Add the class to the element.
         el.nativeElement.classList.add(setAttribute);
       }
    }
}

“您在指令的构造函数中使用ElementRef来注入对宿主 DOM 元素的引用,即您应用了 'directiveName' 的元素。”

我建议查看页面,它非常详细地解释了指令的工作原理。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM