Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a directive conditionally

I am using Material 2 to add md-raised-button. I want to apply this directive only if certain condition becomes true.

For example:

<button md-raised-button="true"></button> 

Another example: I created a basic dynamic reactive form in plunker. I am using formArrayName directive of reactive form for array of controls. I want to apply formArrayName directive only if specific condition becomes true, otherwise don't add formArrayName directive.

Here is a plunker link.

like image 825
user2899728 Avatar asked Jun 16 '17 19:06

user2899728


People also ask

How to apply directive conditionally angular?

Currently, there is NO way to conditionally apply a directive to a component. This is not supported. The components which you have created can be added or removed conditionally. There is already an issue created for the same with angular2 , so it should be the case with angular4 aswell.

What is directive example?

A directive is defined as an order or an official instruction. When your boss orders you to call a client, this is an example of a directive.


1 Answers

If you just need to add an attribute in order to trigger CSS rules, you can use the below method: (this does not dynamically create/destroy a directive)

<button [attr.md-raised-button]="condition ? '' : null"></button>

Applied the same to your plunker: fork

Update:

How condition ? '' : null works as the value:

When its the empty string ('') it becomes attr.md-raised-button="", when its null the attribute will not exist.

Update: plunker update: fork (version issues fixed, please note the question was originally based on angular 4)

like image 140
Aldracor Avatar answered Oct 18 '22 05:10

Aldracor