0

I am wondering how to add dynamic attribute in Angular. By saying that I mean I need to pass the attribute name. something like this:

<button [attr.{{attrName}}]="isAllowedAttribute ? attrValue : null" >{{buttonTitle}}/button>

I already see this question but I wanna pass the attribute by attrName.

Any idea?

Saeid
  • 13,224
  • 32
  • 107
  • 173
  • 2
    I suggest you'll make your own attribute directive, you can do use that attribute as a custom attribute to do what ever you need it to do or to be. https://angular.io/guide/attribute-directives – Hagai Wild Aug 08 '18 at 15:29
  • Have a look at this. https://stackblitz.com/edit/angular-3cqdya?file=src%2Fapp%2Fapp.component.ts, it can be improved obviously, but I guess this is what you require... – Ashish Ranjan Aug 08 '18 at 16:10

2 Answers2

1

You may use a directive to set your dynamic attributes.

Look at https://stackblitz.com/edit/angular-hnjfrg?file=src%2Fapp%2Fdynamic-attr.directive.ts to get a glimpse at how to use it.

You may use the directive like this:

  <p [dynamicAttr]="'color'" attrValue="red"></p>

and access the directive values like this:

  constructor(el: ElementRef) {
    this.element = el;
  }

  ngAfterViewInit() {
    console.log('Dynamic attribute: ', this.dynamicAttr);
    this.element.nativeElement.style[this.dynamicAttr] = this.attrValue;
  }

You may use the hook according to your use case. I have just used ngAfterViewInit to set things up only once the view renders.

Kabb5
  • 3,760
  • 2
  • 33
  • 55
Ankit Sharma
  • 1,674
  • 8
  • 11
0

Write a directive that takes the attribute name and value.

This one takes a "map" of attribute name values.
https://stackblitz.com/edit/angular-how-to-add-dynamically-attribute-by-passing-attribute-n?file=src%2Fapp%2Fapp.component.html

Wilhelmina Lohan
  • 2,803
  • 2
  • 29
  • 58