Anthony
Anthony

Reputation: 463

How to bind multiple attributes to Angular 5 component?

I have a component toolbar with template:

<div *ngFor="let item of items" class="toolbar__item">
  <a href="{{ item.url }}" [attributes]="item.attributes">{{ item.label }}</a>
</div>

I want to bind an array of item.options to an A element. How to do it with Angular 5?

const items = [
  { 'url': 'someurl', 'label': 'Label', 'attributes': {'data-target': '#dropdown', 'data-toggle': 'dropdown'} }
]

Upvotes: 4

Views: 4010

Answers (1)

Aluan Haddad
Aluan Haddad

Reputation: 31803

I expect you could create a directive that would store and assign dynamic attributes to an element but I've not tested it.

import {Directive, ElementRef, Input} from '@angular/core';

@Directive({
  selector: '[dynamicAttributes]'
})
export class DynamicAttributesDirective {
  @Input() dynamicAttributes: {[key: string]: string};

  constructor(public element: ElementRef<HTMLElement>) {}

  ngOnInit() {
    Object.assign(this.element.nativeElement.attributes, this.dynamicAttributes)
  }
}

And you would consume it as follows

<a href="{{item.url}}" [dynamicAttributes]="item.attributes">{{item.label}}</a>

Upvotes: 4

Related Questions