Add attribute with renderer using a directive

后端 未结 2 1967
暖寄归人
暖寄归人 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:40

    If I understood you right.. your idea is good, should work!

    See this plunker: https://plnkr.co/edit/YctUpK9r9AqIk0D1qvgZ?p=preview

    EDIT: updated to use Renderer2

    import {Component, Directive, NgModule, ElementRef, Renderer2, ViewChild} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    
    @Directive({
      selector: '[foo]'
    })
    export class MyFancyDirective {
    
      constructor (private _elRef: ElementRef, private _renderer: Renderer2) { console.log('!'); }
    
      ngOnInit() {
        this._renderer.setAttribute(this._elRef.nativeElement, 'another-fancy-attribute', 'HERE I AM !!');
      }
    
    }
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
          <h2 #header foo (click)="headerClicked()">Hello {{name}}</h2>
        </div>
      `,
    })
    export class App {
    
      @ViewChild('header', { static: true }) header: ElementRef;
    
      name:string;
      constructor() {
        this.name = 'Angular2'
      }
    
      headerClicked() {
        console.dir(this.header.nativeElement.attributes['another-fancy-attribute'].value);
      }
    }
    
    @NgModule({
      imports: [ BrowserModule ],
      declarations: [ App, MyFancyDirective ],
      bootstrap: [ App ]
    })
    export class AppModule {}
    
    0 讨论(0)
  • 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");
          }
        }
    
    0 讨论(0)
提交回复
热议问题