I am currently in the process of constructing a form to generate a POST request to the API. I have opted to utilize Angular Material 4 and incorporate the Autocomplete component provided by Material Design.
Below is the code snippet displaying my HTML Component:
<mat-form-field class="example-full-width">
<input type="text" matInput placeholder="Local" [formControl]="HomeTeamCtrl" [matAutocomplete]="homeAuto">
<mat-autocomplete #homeAuto="matAutocomplete">
<mat-option *ngFor="let team of filteredHomeTeams | async" [value]="team.teamName">
{{ team.teamName }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
Everything is functioning as expected; I am able to input text and filter the results accordingly. Upon selecting an item from the list, it populates the input field and retains the selection.
It's evident that the list filtering is based on a property ('teamName') of the 'Team' object, which is derived from an array of Team[].
The 'Team' object contains several other attributes, and my objective is to trigger a method upon selecting an option from the Autocomplete list. This method should extract a specific string property from the selected object, parse it, and assign it to a variable.
Here is my 'Team' class structure:
export class Team {
teamName: string;
selfLink: string;
}
Initial Array:
"teams": [{
"teamName": "River";
"selfLink": "http://localhost:4200/teams/1"
},
{
"teamName": "Boca";
"selfLink": "http://localhost:4200/teams/2"
}]
Creation of the initial array:
ngOnInit(){
this.match = new Match;
this.availableTeams = [];
this.getTeams();
this.HomeTeamCtrl = new FormControl();
this.filteredHomeTeams = this.HomeTeamCtrl.valueChanges
.startWith(null)
.map(team => team ? this.filterTeams(team) : this.availableTeams.slice());
}
getTeams() {
this.teamService.getTeamsList()
.subscribe(
teams => this.availableTeams = teams,
error => console.log(error)
);
}
filterTeams(name: string) {
return this.availableTeams.filter(team =>
team.teamName.toLowerCase().indexOf(name.toLowerCase()) === 0);
}
The operations are currently running smoothly. However, I have an existing 'match' object that requires data completion before pushing it. Herein lies my inquiry.
The question at hand is:
How can I achieve the following functionality:
Upon selecting a team name from the Autocomplete dropdown, I aim to extract the ID (last number) from the 'selfLink' string of that particular object and assign it to 'this.match.homeTeam'