Add attribute with renderer using a directive

后端 未结 2 1968
暖寄归人
暖寄归人 2021-02-19 02:29

I want to achieve extending an HTML tag with an attribute but encapsulate this with an angular 2 component.

Let\'s assume the original markup using my Angular 2 componen

2条回答
  •  旧巷少年郎
    2021-02-19 02:56

    We can use setAttribute method of Renderer2 class

    import {Directive, ElementRef, Renderer2, Input, HostListener, OnInit} from '@angular/core';
    
    @Directive({
      selector: '[DirectiveName]'
    })
    export class DirectiveNameDirective implements OnInit {
     constructor(public renderer : Renderer2,public hostElement: ElementRef){}
    ngOnInit() {
          this.renderer.setAttribute(this.hostElement.nativeElement, "data-name", "testname");
          }
        }
    

提交回复
热议问题