The data defined in the form element can be accessed and used in controller by using various techniques.
1 Interpolation 2 Two way binding
In Interpolation technique , the reference for form element is defined by using "#" and a value property is used to refer the element value
Syntax:
<input type="text" #uname> { {uname.value }}
Dealing with Forms
Example: Accessing Index over iterations
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
.html changes
<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" >
<th> Product Id</th>
<th> Name </th>
<th> Price </th>
<th> Action </th>
<tr *ngFor= "let item of products; let i=index">
<td> {{ item.Id}}</td>
<td> {{ item.Name}}</td>
<td> {{ item.Price}}</td>
<td> <button (click)= 'DeleteProducts(i)'> Delete </button> </td>
</tr>
</table>
ScreenShot
required for "ngModel".
Output
Output
No comments:
Post a Comment
Thank you for visiting my blog