Marlon_Brendo
Marlon_Brendo

Reputation: 3

Dynamic Property Binding for Angular Directive Inputs

Hi I'm making a a drag directive but because of the way it works I can't get it to work on dynamic objects as it calls the id in the input.

@Input()
set Drag(options: any) {
   this.stickerElement = document.getElementById(options.id);
}

Which works fine when the element isn't dynamic:

<div id="sticker" class="issues" [Drag]="{id: 'sticker'}">

but when it's set dynamically I can't figure out how to interpolate the ID dynamically.

<div [attr.id]="'Session' + Day.id" [Drag]="{id:'Session' + Day.id}"></div>

I've tried setting this.stickerElement with the @HostListener when you use it but that allows the directive to bubble and use child elements. I guess I can work around it but it doesn't feel right.

I feel like I'm missing some knowledge because no matter what I google nothing useful comes up about how to interpolate it correctly. Can you interpolate an attribute into a directive like this?

Thanks in Advance B

Upvotes: 0

Views: 1141

Answers (1)

Barremian
Barremian

Reputation: 31145

I don't see any issue in the interpolation. However, document.getElementById(options.id) in Angular looks dirty. Instead you could use a template reference variable and directly send the HTMLElement.

Try the following

Template

<div appSticker #sticker [Drag]="{ref:sticker}"></div>

Directive

@Directive({ selector: "[appSticker]" })
export class StickerDirective {
  stickerElement: HTMLElement;

  @Input()
  set Drag(options: any) {
    this.stickerElement = options.ref;
  }

  constructor() {}
}

Also I don't see the directive binding in the <div> tag in your code.

Upvotes: 1

Related Questions