Sometimes you need to add some attribute to an HTML element but not always, it only needs to be added conditionally or if some condition is met.
Example,
when filling an account opening form online, nominee name field is enabled only when the user opts to add a nominee else it remains disabled.
This can be done by adding disabled attribute to the nominee name input box when add nominee checkbox is checked.

How to add attribute conditionally
Angular provides support to add an attribute to an HTML element conditionally using the ternary operator. Besides adding the attribute, it is also possible to set its value.
For example, suppose you want to add a maxlength attribute to an input box in which nationality is entered but this attribute should only be added if the country is other than USA.
Also, it should have a value of 5. This can be done as

<input [attr.maxlength] = “country === ‘USA’ ? null : 5″ />

where country is a variable(or field) declared in the corresponding typescript class.
Above condition checks the value of country variable and returns null if its value is not equal to USA else returns 5.
If the value returned is null, then the attribute is not added to the element else maxlength attribute is added with a value of 5.

If the attribute which needs to be added is an inbuilt attribute of the element, then attr. can be omitted.
If the attribute is a custom or user defined attribute, then attr. is required.
Inbuilt attributes include required, maxlength, checked, disabled, class, href etc.

Note that the condition given in the ternary operator can be anything which returns a boolean value(true or false). Similarly, it is also possible to add required attribute to an element.

2
Close Menu

Never Miss an article !

Get the new post delivered straight into your inbox, enter your email and hit the button

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

codippa will use the information you provide on this form to be in touch with you and to provide updates and marketing.