Add attribute using visualizer using directive

I want to achieve an extension of an HTML tag with an attribute, but encapsulate it with an angular 2 component.

Suppose the original markup uses my angular 2 foo component

<div foo="x"></div> 

The foo attribute should convert the div to:

 <div some-other-fancy-attribute="x"></div> 

At first I tried to implement the directive, but I could not figure out how to add another attribute to the hosting element using Renderer from angular / core.

Then I read about angular 2 components using an attribute selector like [foo]. I liked the idea of ​​using a template to display the some-other-fancy attribute.

However, the template gets render AFTER the tag, so I get:

 <div foo="x">some-other-fancy-attribute="x" 

Is there an easy way to encapsulate the creation of an attribute? Thought it was trivial, but it gives me more headache than expected.

+5
source share
2 answers

If I understand you correctly. your idea is good, should work!

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

 import {Component, Directive, NgModule, ElementRef, Renderer, ViewChild} from '@angular/core' import {BrowserModule} from '@angular/platform-browser' @Directive({ selector: '[foo]' }) export class MyFancyDirective { constructor (private _elRef: ElementRef, private _renderer: Renderer) { console.log('!'); } ngOnInit() { this._renderer.setElementAttribute(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') 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 {} 
+10
source

We can use the setAttribute method of the 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"); } } 
+5
source

All Articles