Example Iteration for even and Odd Properties
Apply a CSS Class to a table row over iteration.
Syntax:
<tr class="className>
[class.ClassName]=true/false
Add a new Component
ng g c datatable
Goto datatablecomponent.ts and write the below code
@Component({
selector: 'app-datatable',
templateUrl: './datatable.component.html',
styleUrls: ['./datatable.component.css']
})
export class DatatableComponent {
public products =[
{ Id:1, Name:'Samsung TV',Price :5669},
{ Id:2, Name:'Sony TV',Price :6669}
];
public txtName: any;
public txtPrice:any;
public id=this.products.length;
public confirmDelete:any;
public AddProducts() {
this.id++;
this.products.push( {Id:this.id,Name:this.txtName,Price:this.txtPrice});
alert('Record Inserted');
this.txtName='';
this.txtPrice='';
}
public DeleteProducts(index:any) {
this.confirmDelete=confirm('Are you sure, want to Delete ?');
if(this.confirmDelete==true)
{
this.products.splice(index,1);
}
}
}
ScreenShot
.CSS File Changes
.odd
{
background-color: darkblue;
color: white;
}
.even
{
background-color: darkgreen;
color:white;
}
.headerstyle
{
background-color: red;
color:white;
}
ScreenShot
<fieldset>
<legend> Add Products </legend>
<dl>
<dt>Name</dt>
<dd> <input type="text" [(ngModel)]="txtName"></dd>
<dt>Price</dt>
<dd> <input type="text" [(ngModel)]="txtPrice"></dd>
</dl>
<br/>
<button (click) ='AddProducts()' >Add Product</button>
</fieldset>
<h3> Products List</h3>
<table width="400" border="1" >
<thead class="headerstyle">
<th> Product Id</th>
<th> Name </th>
<th> Price </th>
<th> Action </th>
</thead>
<tr [class.even]="even" [class.odd]="odd" *ngFor= "let item of products; let i=index; let odd=odd;let even=even">
<td> {{ item.Id}}</td>
<td> {{ item.Name}}</td>
<td> {{ item.Price}}</td>
<td> <button (click)= 'DeleteProducts(i)'> Delete </button> </td>
</tr>
</table>
ScreenShot
appModule.ts
required for "ngModel".
Good Site
ReplyDelete