I am working on Angular2 project and want to want to add rows to table dynamically, when a button is clicked. I know that *ngFor
can be used to add rows dynamically, but I am interested if it is possible to use *ngFor
only if button is clicked.
usually you use *ngFor to iterate over an array (generally of objects). So if your array is called "data" yo can have some like
<table *ngIf="data.length"> <!--Don't show nothing if no data-->
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr *ngFor="let item of data">
<td>{{item.firstName}}</td>
<td>{{item.lastName}}</td>
<td>{{item.age}}</td>
</tr>
</table>
Where you has a variable data like
data:any[]=[] //don't forget initialize!
A button can execute some like
onClick()
{
this.data.push({firstName:"firstName",lastName:"Last Name",age:18})
}
A quick sample:
<button (onClick)="sth=!sth">click</button>
<div *ngIf="sth">
<div *ngFor="...">
...
</div>
</div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.