Class binding Class binding works with component to view template. See the
below simple example. Gradually we will add more on it.
Now we will add a style class to
the button In the below example we have
added class=’colorClass’ and [class]=’classToApply’ which value
is coming from the component. In this case [class]=’classToApply’
overrides the class=’colorClass’. And applies classesToApply string = 'italicsClass boldClass' Below is
the output.
We can Add or remove a single class To add or remove a single class, include the
prefix 'class' in a pair of s uare brackets, followed by a DOT and then the
name of the class that you want to add or remove.
In this case both
colorClass and applyBoldClass are applied.
The same output will come by changing the below code
<button
class='colorClass' [class.boldClass]='!applyBoldClass'>My
Button</button>
applyBoldClass boolean = false;
You can
also remove an existing class that is already applied.
<button class='colorClass
boldClass italicsClass'
[class.boldClass]='applyBoldClass'>My Button</button>
applyBoldClass boolean = false;
Add or
remove multiple classes use ngClass directive
<button class='colorClass'
[ngClass]='addClasses()'>My Button</button>
applyBoldClass boolean = true;
applyItalicsClass boolean = true;
addClasses() {
let classes = {
boldClass this.applyBoldClass,
italicsClass this.applyItalicsClass
};
return classes;
}
No comments:
Post a Comment