Reputation: 15
In angular 4 .ts i want to use both accounts.Id and accounts.Name from dropdown. can it be possible?
<select [(ngModel)]="selectedName" class="form-control" (change)="SearchLedgerTransaction($event.target.value)">
<option value=""></option>
<option *ngFor="let accounts of accountledger" [value]="accounts.Id && accounts.Name">
{{accounts.Name}}
</option>
</select>
<br />
{{selectedName}} Account Ledger View
Upvotes: 1
Views: 12402
Reputation: 8269
If you have a long list of accountledger and want to fetch its id and name only, you can try this method:
<option *ngFor="let accounts of accountledger"
[ngValue]="{id: accounts.Id, name: accounts.Name}"> // Use ngValue for multi-select control. Setup the object value you want to assign to the 'selectedName' model
{{accounts.Name}}
</option>
Then, your selectedName model value will become, example: { id: 1, name: 'Kristy' }
Had created a Stackblitz Demo for your reference.
UPDATE
1.) On your select, you can specify [ngModel] and (ngModelChange) separately.
<select [ngModel]="selectedName"
(ngModelChange)="onSelectName($event)" // Call onSelectName function if select is actively changed
class="form-control" >
<option value=""></option>
<option *ngFor="let accounts of accountledger"
[ngValue]="{ id: accounts.Id, name: accounts.Name }"> // Pass Id and Name
{{accounts.Name}}
</option>
</select>
On your Component - Destructure the parameter as the current event value is the passed { id: accounts.Id, name: accounts.Name } from select box [ngValue]
onSelectName({id, name}): void {
this.selectedName = name; // Not Recommended; With this, you can now reset the selectedName value to just the name value
this.name = name; // Create new variable to store the name, if you will reassign the selectedName model value which holds ID and Name based on the template [ngValue], it will not reflect the updated data if you reassign it to just name. I suggest you create new one that acts as your official model name to store the selected name.
console.log(id); // and fetch its ID as well, depends on how you want to use this.
}
Upvotes: 3
Reputation: 396
you can use something like..
<select [(ngModel)]="selectedName" class="form-control" (change)="SearchLedgerTransaction($event.target.value)">
<option value=""></option>
<option *ngFor="let accounts of accountledger" [value]="accounts">
{{accounts.Name}}
</option>
</select>
<br />
{{selectedName.Id}}{{selectedName.Name}} Account Ledger View
Upvotes: 0