1

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?

2
  • 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. angular.io/guide/attribute-directives Commented Aug 8, 2018 at 15:29
  • Have a look at this. stackblitz.com/edit/…, it can be improved obviously, but I guess this is what you require... Commented Aug 8, 2018 at 16:10

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.