Angular NgStyle and NgClass statements are used to apply CSS styling to HTML elements. These two directives are very useful in customizing the appearance of web pages.
With Angular NgStyle, you can set the style of an element using a JavaScript object.
For example, you can set the color, width, and height of an element. With NgClass, you can set the class of an element using a JavaScript object.
Angular ngClass is Angular directive that can be used to dynamically set the class of an element also use ngClass in angular with condition.
Angular ngStyle allows you to set the style of an element using a JavaScript object, while NgClass lets you set the class of an element using a space-delimited string.
Both directives can be used together to create dynamic and powerful Angular applications.
Call a function inside ngstyle
export class PageComponent {
getFlagColor(country: string) {
switch (country) {
case 'INDIA':
return '#eb9210';
case 'PAKISTAN':
return '#0dc34a';
case 'ENGLAND':
return '#fd1515';
case 'AUSTRALIA':
return '#0d36c3';
case 'FRANCE':
return '#e110eb';
default:
return '#eb9210'
}
}
countries: any[] = [
{
"name": "France",
"country": 'FRANCE'
},
{
"name": "India",
"country": 'INDIA'
},
{
"name": "Pakistan",
"country": 'PAKISTAN'
},
{
"name": "Australia",
"country": 'AUSTRALIA'
},
{
"name": "England",
"country": 'ENGLAND'
}
];
}
<div>
<ul *ngFor="let country of countries">
<li [ngStyle]="{'color':getFlagColor(country)}"> {{ country.name }}</li>
</ul>
</div>
//--------or you could use--------------
<div>
<ul *ngFor="let country of countries">
<li [style.color]="getFlagColor(country)"> {{ country.name }}</li>
</ul>
</div>
Output:
Call a function inside ngClass
studentsObj = [
{ name: 'yogesh', status: 0 },
{ name: 'Akash', status: 1 },
{ name: 'Vivek', status: 2 },
{ name: 'lovekesh', status: 0 },
{ name: 'Ankush', status: 1 },
{ name: 'Neeraj', status: 1 },
];
getClass(status: number) {
switch (status) {
case 0:
return '';
case 1:
return 'active';
case 2:
return 'unactive';
default:
return 'unactive';
}
}
// Some css for the reference
.student {
border: none;
outline: none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
font-size: 18px;
}
.active, .btn:hover {
background-color: #666;
color: white;
}
<div id="myDIV">
<ng-container *ngFor="let student of studentsObj">
<button class="btn" [ngClass]="getClass(student.status)">{{student?.name}}</button>
</ng-container>
</div>
0 Comments