Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally add directives

Tags:

angular

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?

like image 328
Neoheurist Avatar asked Aug 03 '16 14:08

Neoheurist


People also ask

What are types of directives and give example of attribute directives?

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.

What is restrict option in 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.


1 Answers

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

like image 89
Günter Zöchbauer Avatar answered Oct 28 '22 05:10

Günter Zöchbauer