I have an json object in the following form:
[{"userAccountId":4544,"userAccountName":"Raj Tera (rtera)"},{"userAccountId":103561,"userAccountName":"Raphael Wouters (rwouters)"}]
Following is the code that I have used for displaying and filtering out accounts.
<input class="form-control" type="text" placeholder="Pick one" matInput [matAutocomplete]="auto" name="tempAccount" [(ngModel)]="tempAccount" (ngModelChange)="filteredUserAccounts = filterUserAccounts(tempAccount)" #tempAccountName=ngModel>
<mat-autocomplete [displayWith]="displayFn(filteredUserAccounts)" #auto="matAutocomplete">
<mat-option *ngFor="let x of filteredUserAccounts" [value]="x.userAccountName">
{{x.userAccountName}}
</mat-option>
</mat-autocomplete>
tempAccount I am using to pass the string. So that I can filter out the content. Here are additional TS file code:
filterUserAccounts(val: string) {
console.log('tesasfsdasdfasfd!!!!')
if (val) {
const filterValue = val.toLowerCase();
var test=this.userAccounts;
return this.userAccounts.filter(state => state.userAccountName.toLowerCase().includes(filterValue));
}
return this.userAccounts;
}
displayFn(user?: UserAccount): string | undefined {
return user ? user.userAccountName : undefined;
}
The result I want is that my model should give id so that I can save that in DB and it should display the name. I am able to filter out the data but not able to bind it to model. Any help would be highly appreciated.
Try using the whole object as model so instead of [value]="x.userAccountName"
use [value]="x"
Change your filter function to
filterUserAccounts(user: UserAccount) {
const val = user.userAccountName;// define val from user
console.log('tesasfsdasdfasfd!!!!')
if (val) {
const filterValue = val.toLowerCase();
var test=this.userAccounts;
return this.userAccounts.filter(state => state.userAccountName.toLowerCase().includes(filterValue));
}
return this.userAccounts;
}
Then when you observe the ngModel tempAccount.userAccountId
should give you the id and temAccount.userAccountName
should give you name
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.