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.
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.
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
maxlengthattribute 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″ />
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.
attr.can be omitted.
If the attribute is a custom or user defined attribute, then
Inbuilt attributes include
false). Similarly, it is also possible to add
requiredattribute to an element. 15