0
0
Angularframework~30 mins

ngClass for dynamic classes in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using ngClass for Dynamic Classes in Angular
📖 Scenario: You are building a simple Angular component that displays a list of tasks. Each task can be marked as completed or pending. You want to highlight completed tasks with a green background and pending tasks with a yellow background.
🎯 Goal: Create an Angular standalone component that uses ngClass to dynamically apply CSS classes based on each task's completion status.
📋 What You'll Learn
Create a list of tasks with exact names and completion status
Add a boolean variable to track if a task is completed
Use ngClass to apply CSS classes dynamically
Add CSS classes for completed and pending tasks
Use a standalone Angular component with signals and new control flow
💡 Why This Matters
🌍 Real World
Dynamic styling is common in real apps to show status, errors, or user actions visually. Using ngClass helps keep templates clean and maintainable.
💼 Career
Understanding ngClass and dynamic styling is essential for Angular developers to build interactive and accessible user interfaces.
Progress0 / 4 steps
1
Set up the tasks array
Create a standalone Angular component named TaskListComponent with a tasks array containing these exact objects: { name: 'Buy groceries', completed: false }, { name: 'Walk the dog', completed: true }, and { name: 'Read a book', completed: false }.
Angular
Need a hint?

Define the tasks array exactly as shown inside the component class.

2
Add CSS classes for task status
Add a styles array to the @Component decorator with two CSS classes: .completed that sets background-color: lightgreen; and .pending that sets background-color: lightyellow;.
Angular
Need a hint?

Add the styles property inside the @Component decorator with the two CSS classes.

3
Use ngClass to apply dynamic classes
In the component's template, add an unordered list <ul>. Use *ngFor="let task of tasks" to loop over tasks. For each <li>, use [ngClass] to apply the class 'completed' if task.completed is true, otherwise apply 'pending'. Display the task's name inside the <li>.
Angular
Need a hint?

Use *ngFor to loop and [ngClass] with a ternary expression to apply classes.

4
Add accessibility and finalize component
Add an aria-label attribute with value "Task list" to the <ul> element for accessibility. Also, add a tabindex="0" attribute to the <ul> to make it keyboard focusable.
Angular
Need a hint?

Add aria-label="Task list" and tabindex="0" to the <ul> tag for accessibility.