I am new to angular and I am trying to solver for the following. Spent almost 3 hours going through docs and YouTube videos but no luck.
Use Case - Change the button color based on the status coming form a data feed. For example: Button is blue if the feed.status is Open. It is green if feed.status is closed and it is red if feed.status is paused.
Inside my component.ts file -
feedData: any;
show="Open";
..... more code that completes the component implementation
In my component.html file
<ion-card *ngFor="let feed of feedData">
<div *ngIf="show == feed.status">
<ion-item lines="none">
<ion-button slot="start" color="red">{{ feed.status }}</ion-button>
</ion-item>
</div>
</ion-card>
The code above doesn't work. What i really need to do is change the color based on the value stored in feed.status. How do I go about it?
CodePudding user response:
Following is the code
HTML
<ion-list>
<ion-item
*ngFor="let f of feeds"
[ngClass]="{
'open-status': f.status == 'Open',
'closed-status': f.status == 'Closed',
'paused-status': f.status == 'Paused'
}"
>
<div>{{ f.label }}</div>
</ion-item>
</ion-list>
CSS
.open-status{
color:blue;
}
.closed-status{
color: green;
}
.paused-status{
color: red;
}
COMPONENT
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
feeds = [
{
label: 'Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,', status: 'Open'
},
{
label: 'Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,', status: 'Closed'
},
{
label: 'Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,', status: 'Paused'
},
{
label: 'Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print,', status: 'Open'
},
]
}
CodePudding user response:
The important part of Nathash Kumar's answer is the [ngClass].
If we take your code:
<ion-card *ngFor="let feed of feedData">
<div *ngIf="show == feed.status">
<ion-item lines="none">
<ion-button slot="start" [ngClass]="{
'open-status': f.status == 'Open',
'closed-status': f.status == 'Closed',
'paused-status': f.status == 'Paused'
}">{{ feed.status }}</ion-button>
</ion-item>
</div>
</ion-card>
What does ngClass do? It adds the class to the button depending on the f.status value. You can access it afterwards via css and change everything needed there.
Another tip, use enums if you reuse that status more often, so you do not get in trouble with spelling mistakes.
export enum FeedStatus {
OPEN = 'Open',
CLOSED = 'Closed',
PAUSED = 'Paused',
}
Than you can import it in your component file like that:
public feedStatus: typeof FeedStatus = FeedStatus;
afterwards you can access it in html via
...f.status == feedStatus.OPEN
Check https://www.vitamindev.com/angular/how-to-use-enum-in-html/ for more informations regarding the use of enums in your template.