0

Based on this host attribute post, I've created this Plunker.

After reading the github issue, my understanding is that we should be able to use [attr.someDirective] to conditionally apply a directive attribute to an element.

It does appear to add/remove the directive attribute as one would expect. However, the Plunker demonstrates that - when using attr - even when the directive arribute is added to the element, the directive never gets applied.

Am I missing something here, or is this not the way the attr host attribute works?

Kizmar
  • 2,465
  • 3
  • 20
  • 27

1 Answers1

1

For attr.anyDirective to work, the anyDirective (without any value) should be included in the element (in html template). See below (shown in bold):


Option-1 (Set as blank will render directive without value)

<input type="text" name="one" phoneMask [attr.phoneMask]="" [(ngModel)]="input_one">

<input type="text" name="one" phoneMask [(ngModel)]="input_one">

Option-2 (Set as "null" will not render the directive)

<input type="text" name="one" phoneMask [attr.phoneMask]="null" [(ngModel)]="input_one">

<input type="text" name="one" [(ngModel)]="input_one">

Option-3 (Set as "some_value" will not render the directive with "some_value)

<input type="text" name="one" phoneMask [attr.phoneMask]="some_value" [(ngModel)]="input_one">

<input type="text" name="one" phoneMask="some_value" [(ngModel)]="input_one">

I have tested the above in the plunk provided by you and it works.

Hope this helps you.

Santanu Biswas
  • 4,699
  • 2
  • 22
  • 21
  • Upon further investigation, this isn't working the way I need/want it to. I updated the plunk to include `phoneMask` on it's own as you show in the examples. The third input should NOT have the directive applied (and the attribute isn't on the element), but it's still firing the `onInputChange` function of the directive. – Kizmar Jan 26 '17 at 20:50
  • The firing of `onInputChange` has no relation with presence/absence of the directive (attribute) in the element. The `onInputChange` is firing because you have set `@HostListener('ngModelChange', ['$event'])` in the custom directive. If you want to avoid `onInputChange` event effect, you must return from the `onChangeInput` by doing `if (!this.phoneMask) return;`. – Santanu Biswas Jan 26 '17 at 21:11
  • That's what I was afraid of. That means the third party directive I'm using needs to be altered. – Kizmar Jan 26 '17 at 21:13
  • If it is a open-source third party directive, you can ask them the reasoning behind firing `onEventChange` when the attribute is missing. If there is no reasoning and its a bug, maybe you can do a pull-request and submit the above solution. – Santanu Biswas Jan 26 '17 at 21:16