简体   繁体   English

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

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

How would you do to add and set an HTML class that can be changed with a parameter, with an Angular directive?您将如何使用 Angular 指令添加和设置可以通过参数更改的 HTML class? Let's say we have a div with an already existing class, but no directive:假设我们有一个已经存在 class 的 div,但没有指令:

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

Now, we want to attach a directive to it, and one parameter:现在,我们要为其附加一个指令和一个参数:

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

If I need a 4, then my class added dynamically would be changed like that:如果我需要 4,那么我动态添加的 class 将像这样更改:

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

I totally know how to add a class with @hostbinding, but I can't find how to change this one dynamically with my "set" parameter我完全知道如何使用@hostbinding 添加一个 class,但我找不到如何使用我的“设置”参数动态更改这个

Thank you very much非常感谢

If I understood your question correctly, this might be accomplished as follows:如果我正确理解了您的问题,则可以按如下方式完成:

I did this from memory, maybe something is not working as expected but I think you get the gist of it.我是从 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);
       }
    }
}

"You use the ElementRef in the directive's constructor to inject a reference to the host DOM element, the element to which you applied 'directiveName'." “您在指令的构造函数中使用ElementRef来注入对宿主 DOM 元素的引用,即您应用了 'directiveName' 的元素。”

I would suggest checking this page out, it explains in quite a bit of detail how directives work.我建议查看页面,它非常详细地解释了指令的工作原理。

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

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