I am trying to delete/remove the button from the array of 1st and 2nd index loop and display only at last index value or loop.
below is the code for approach:
import {
Component,
OnInit
} from '@angular/core';
import {
FormGroup,
FormControl
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular';
userForm = new FormGroup({
name: new FormControl(),
age: new FormControl()
});
masterData = [{
name: 'alex',
age: 20,
button: 'no'
},
{
name: 'bony',
age: 21,
button: 'no'
},
{
name: 'acute',
age: 23,
button: 'yes'
}
]
ngOnInit() {
}
html:
<div *ngFor="let data of masterData">
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
Name: <input formControlName="name" placeholder="Enter Name"> Age: <input formControlName="age" placeholder="Enter Age">
<button type="submit">Submit</button>
<button type="button">display at last </button>
</form>
</div>
The above is the code in which the the array of object is integrated, where the 'display at last" button should be displayed only for the last object of the array.
The approached is followed is to get the element-ref of the button from dom but it dint work. Please help me to solve this issue
For better understanding here is a link of code: https://stackblitz.com/edit/angular-chdfdh?file=src%2Fapp%2Fapp.component.ts
You can get the index from the *ngFor
, like so:
<div *ngFor="let data of masterData; let last = last">
<form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
Name: <input formControlName="name" placeholder="Enter Name"> Age: <input formControlName="age" placeholder="Enter Age">
<button type="submit">Submit</button>
<button type="button" *ngIf="last">display at last </button>
</form>
</div>
So what is happening is that I am adding a variable called last
to the last item of the for loop. Then only displaying the button if the variable is true, i.e. last item.
EDIT
I see that there is also a variable in the masterData
. You can just use the variable from that to display the button.
For example:
<div *ngFor="let data of masterData; let last = last">
...
<button type="button" *ngIf="data.button === 'yes'">display at last </button>
</form>
</div>