Reputation: 265
I am new to angular. I am iterating through an array of objects. I have declared two buttons that is Start & End. I want to display the start initially for each item. when user click on Start button of an item that item's start button should hide & End button should display.
startTask(id) {
console.log('item id',id)
}
EndTask(index) {
console.log('item id',id)
}
<div class="row no-gutters">
<div class="card width hr" *ngFor="let item of allUserTaskArr">
<div class="card-header">
{{item.due | date}}
</div>
<div class="card-body pad-125">
<div class="row no-gutters">
<div class="col-md-12">
{{item.name}}
<div class="float-right">
<button class="btn btn-info mar-l-r-0-5" (click)="startTask(item.id)">Start</button>
<button class="btn btn-danger mar-l-r-0-5" (click)="EndTask(item.id)">End</button>
</div>
</div>
</div>
</div>
</div>
</div>
In the above example, each item has a unique ID. for each item there is one start & end button. I want to display the start button initially for all & when I click on the Start button of an item only that button should replace with End button. all others should remain the same.
[![ngFor items image]]: https://i.sstatic.net/9pvLE.png
Upvotes: 0
Views: 2042
Reputation: 659
first you need extra property like button of that array
.ts file
allUserTaskArr = [
{
'name': 'abc',
'id':1,
'button': 'start',
},
{
'name': 'xyz',
'id':1,
'button': 'end',
}
];
public startTask (item) {
item.button = 'end';
}
public endTask (item) {
item.button = 'start';
}
and .html file is
<div class="card width hr" *ngFor="let item of allUserTaskArr">
<div class="card-header">
{{item.due | date}}
</div>
<div class="card-body pad-125">
<div class="row no-gutters">
<div class="col-md-12">
{{item.name}}
<div class="float-right">
<button class="btn btn-info mar-l-r-0-5" *ngIf="item.button =='start'" (click)="startTask(item)">Start</button>
<button (click)="endTask(item)" class="btn btn-danger mar-l-r-0-5" *ngIf="item.button =='end'">End</button>
</div>
</div>
</div>
</div>
</div>
another way Button change by index .html file
<div class="card width hr" *ngFor="let item of allUserTaskArr; let i = index">
<div class="card-header">
{{item.due | date}}
</div>
<div class="card-body pad-125">
<div class="row no-gutters">
<div class="col-md-12">
{{item.name}}
<div class="float-right">
<button class="btn btn-info mar-l-r-0-5" *ngIf="item.button =='start'" (click)="startTask(item, i)">Start</button>
<button (click)="endTask(item, i)" class="btn btn-danger mar-l-r-0-5" *ngIf="item.button =='end'">End</button>
</div>
</div>
</div>
</div>
</div>
.ts file
allUserTaskArr = [
{
'name': 'abc',
'id':1,
'button': 'start',
},
{
'name': 'xyz',
'id':1,
'button': 'end',
}
];
public startTask (item, index) {
this.allUserTaskArr[index].button = 'end';
}
public endTask (item, index) {
this.allUserTaskArr[index].button = 'start';
}
Upvotes: 1