I want to conditionally add a directive to a component (where au-disabled
, au-accented
, and au-focused
are the directives):
<template [ngIf]="disabled">
<au-placeholder au-disabled></au-placeholder>
</template>
<template [ngIf]="accented">
<au-placeholder au-accented></au-placeholder>
</template>
<template [ngIf]="focused">
<au-placeholder au-focused></au-placeholder>
</template>
The above approach works (and is somewhat acceptable to me) because (in my case) the conditional properties disabled
, accented
, and focused
are mutually exclusive - my question arises in cases where the conditional properties are not mutually exclusive (requiring an [ngIf]
for every permutation to apply the corresponding inflected form):
<!-- all of the prior <template [ngIf]= ... -->
<!-- plus -->
<template [ngIf]="disabled && accented">
<au-placeholder au-disabled au-accented></au-placeholder>
</template>
<template [ngIf]="disabled && accented && focused">
<au-placeholder au-disabled au-accented au-focused></au-placeholder>
</template>
<!-- etc -->
Using the following allows my code to handle the combinations with less HTML:
<au-placeholder [au-disabled]="disabled" [au-accented]="accented" [au-focused]="focused"></au-placeholder>
but the rendered HTML always has all of the directives each carrying a truth value... the component must test the truth value of each directive to respond appropriately, but it would be cleaner to not even have irrelevant directives applied. Is there a better way to do this?
The attribute directive changes the appearance or behavior of a DOM element. These directives look like regular HTML attributes in templates. The ngModel directive which is used for two-way is an example of an attribute directive.
Note: When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option. The restrict option is typically set to: 'A' - only matches attribute name. 'E' - only matches element name.
This is not supported. Only components can be added/removed conditionally.
What you can do is to pass a value to make the directive aware that it should'nt do anything.
See also https://github.com/angular/angular/issues/5332
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With