How to get id from list when text input match or equal items exist on list?

19 views
Skip to first unread message

ahmed elbarbary

unread,
Dec 26, 2019, 1:12:14 AM12/26/19
to Angular and AngularJS discussion

problem

How to get id from list when text input match or equal items exist on list ?

I work on angular 7

I have input text on nvabar.Component.html write on it part name as following :

   
 <mat-form-field class="example-full-width"> <input matInput placeholder="Enter name" [(ngModel)]="partname" > </mat-form-field>

I need when write on text input Transistor part then I will search on list parts and get partid =2 .

navbar.component.ts
 export class NavBarComponent implements OnInit { public parts = [ { id: 1, partname: 'hummer', }, { id: 2, partname: 'Transistor', }, { id: 3, partname: 'Air', } ]; ngOnInit() { }

So How to get partid from list when text box text matched items on list ?

Olaleye Israel

unread,
Dec 26, 2019, 7:59:45 AM12/26/19
to ang...@googlegroups.com
<mat-form-field class="example-full-width">
<input matInput placeholder="Enter name" [(ngModel)]="partname" (click)="onClick(partname)">
</mat-form-field>

note: i guess you can pass in partname since you are binding the html value or something to a prop of your component into onClick but i really do not ngModel. whatever it is i believe you can figure.

but, this is what i would do:
I'd use a template reference variable

<mat-form-field class="example-full-width">
<input matInput placeholder="Enter name" [(ngModel)]="partname" (keyup)="onClick(el)" #el>
</mat-form-field>

interface partProps {
id: number;
partname: string;
}

somewhere in your component:
public onClick(el: any): void {
const {id} = this.searchParts(el.id);
   console.log({id});
}

// i strongly suggest that you use a service for all this, considering convention and best practice
private searchParts(name: string): partsProps {
return this.parts.find((cur) => {
return cur.partname === name;
});
}


--
You received this message because you are subscribed to the Google Groups "Angular and AngularJS discussion" group.
To unsubscribe from this group and stop receiving emails from it, send an email to angular+u...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/angular/15452628-b314-489f-a573-06b4263636b7%40googlegroups.com.

Olaleye Israel

unread,
Dec 26, 2019, 1:33:29 PM12/26/19
to ang...@googlegroups.com


I realize I made a mistake: it should be el.value instead of el.id. And, ngmodel would do too.
Thanks
Reply all
Reply to author
Forward
0 new messages