Toggling tasks in our task list

Add the following method to your TasksComponent controller class. Its functionality is pretty basic; we just literally toggle the value of the queued property for a given Task object instance:

toggleTask(task: Task): void {
task.queued = !task.queued;
}

Now, we just need to hook it up with our view buttons. Update our view to include a click attribute (wrapped in braces so that it acts as an output property) in the button created within the ngFor loop. Now that we will have different states in our Task objects, let's reflect this in the button labels by implementing an ngSwitch structure all together:

<table class="table">
<thead>
<tr>
<th>Task ID</th>
<th>Task name</th>
<th>Deliver by</th>
<th>Units to ship</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let task of tasks; let i = index">
<th scope="row">{{i}}
<span *ngIf="task.queued" class="label label-info">Queued</span>
</th>
<td>{{task.name | slice:0:35}}
<span [hidden]="task.name.length < 35">...</span>
</td>
<td>{{ task.deadline | date:'fullDate'}}
<span *ngIf="task.deadline < today" class="label label-danger">Due</span>
</td>
<td class="text-center">{{task.hoursLeft}}</td>
<td>
<button type="button"
class="btn btn-default btn-xs"
(click)="toggleTask(task)"
[ngSwitch]="task.queued">
<ng-template ngSwitchCase="false">
<i class="glyphicon glyphicon-plus-sign"></i>
Add
</ng-template>
<ng-template ngSwitchCase="true">
<i class="glyphicon glyphicon-minus-sign"></i>
Remove
<ng-template>
<ng-template ngSwitchDefault>
<i class="glyphicon glyphicon-plus-sign"></i>
Add
</ng-template>
</button>
</td>
</tbody>
</table>

Our brand new button can execute the toggleTask() method in our component class, passing as an argument the Task object that corresponds to that iteration of ngFor. On the other hand, the preceding ngSwitch implementation allows us to display different button labels and icons depending on the state of the Task object at any given time.

We are decorating the newly created buttons with font icons fetched from the Glyphicons font family. The icons are part of the Bootstrap CSS bundle we installed previously and are in no means related to Angular. Feel free to skip its use or to replace it by another icon font family.

Execute the code as it is now and check out the results yourself. Neat, isn't it? But, maybe we can get more juice from Angular by adding more functionality to the task list.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset