Is there a way for me to set a variable in my component with a value from the Angular Material autocomplete feature?

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'

Answer №1

To easily assign a local variable, you can bind to the md-option (onSelectionChange) event.

<mat-option *ngFor="let team of filteredHomeTeams | async" [value]="team.teamName" (onSelectionChange)="match.homeTeam = team.selfLink">

Alternatively, you can call a function in your component.

**.html**
<mat-option *ngFor="let team of filteredHomeTeams | async" [value]="team.teamName" (onSelectionChange)="parseHomeTeam(team)">

**.component**
parseHomeTeam(team: Team) {
  // Add team parsing logic here
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering an undefined property error while trying to access index '0' in Angular 6 with Angular Material's mat-radio-group component, specifically when attempting to set a dynamic variable within

Currently, I am working with Angular 6 and Angular Material. My project involves a dynamic list of polls with various options. I am attempting to display the selected option using two-way data binding. However, due to the dynamic nature of my list, I have ...

Hiding the keypad on an Android device in an Ionic app when user input is detected

I am currently utilizing the syncfusion ej2 Calendar plugin for a datepicker, but I am only using options such as selecting ranges like today, 1 month, or last 7 days from the plugin itself. The plugin provides dropdown options when the calendar is trigger ...

Resetting Laravel passwords without relying on user emails, with the additional use of Angular for the front end interface

I'm currently working on a laravel-angular application that requires a password reset feature. However, the default password-reset in Laravel relies on email verification, which is not necessary for this particular application. I tried setting $confir ...

Specialized spinning tool not in sight

Having an angular 11 application with a spinner that should be visible during data loading from the backend. However, when the fa-icon is pressed by the user, it becomes invisible while waiting for the server response. The issue arises when the spinner its ...

Angular error TS2531: Object may be null

Within my Component.html file, I have an input field set up like this: <input type="text" (change) = "setNewUserName($event.target.value)"/> The code within the component.ts file looks like this: import { Component } from "@ ...

Steps for obtaining the current state array post re-ordering column in Angular datatables

I am facing an interesting scenario where I can successfully retrieve the current state of an array of columns using pure JS + jQuery, but unfortunately, the same approach does not seem to work in Angular 12! Despite going through the documentation for Ang ...

Looking to include a badge within the nebular menu

Can someone assist me with adding a badge to the Nebular menu to display the inbox count dynamically? Any help would be greatly appreciated. Thanks! import { NbMenuItem } from '@nebular/theme'; export const MENU_ITEMS: NbMenuItem[] = [ { ti ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Syntax highlighting in VSCode does not seem to be functional when the ?? nullish coalescing operator is being utilized

Hello there! I've recently started using react.js with typescript on a new computer, but I've encountered an issue with syntax highlighting in VSCode. It seems that the problem arises when there's a double question mark (??) in the code, spe ...

Ways to retrieve element values within Angular

Here is an example of an element: <li class="someClass">value1<span>value2</span></li> This list element is created using vanilla JavaScript, and a click event is bound to it as demonstrated below: const list = Array.from(documen ...

Connecting extra parameters to an event listener

Scenario: I am facing a situation where my event handler is already receiving one parameter (an error object). However, I now need to pass an additional parameter when binding the event handler. I am aware of the bind() method, but I am concerned that it ...

Leverage the power of an Angular component for repeated

Attempting to recycle an Angular component within the given tree structure. https://i.sstatic.net/LVvwO.png The desired component, existing-savings, is located in transfer-guide. Trying to utilize this component in retirement-contributions-information. ...

Tips for transforming TypeScript Enum properties into their corresponding values and vice versa

Situation Imagine having an enum with string values like this: enum Fruit { Apple = "apple", Orange = "orange", Banana = "banana", Pear = "pear" } Users always input a specific string value ("apple", "banana", "orange", "pear") from a drop-down li ...

Is there any advice for resolving the issue "In order to execute the serve command, you must be in an Angular project, but the project definition cannot be located"?

Are there any suggestions for resolving the error message "The serve command requires to be run in an Angular project, but a project definition could not be found."? PS C:\angular\pro\toitsu-view> ng serve The serve command requires to be ...

Tips for converting a string array constant into a union type

I have a string array that I want to use to create a new type where the properties correspond to the elements in the array. There are different types of arrays and I have a function that generates different output types based on the input array. const RG ...

What is the reason for the compatibility issue between sass-loader and Angular?

One of my rules for dealing with sass is as follows: { test: /\.(scss|sass)$/, use: [ { loader: 'raw-loader'}, { loader: 'sass-loader', options: {data: sassConfiguration} } ], } typescript loader { ...

Accessing attributes of a parent class object from within a child object

Imagine having four tabs within an Angular component, each with its own set of criteria for being displayed. Here's a high-level overview of the scenario. export class DisplayTabs { foo: true; bar: false; tabs: { 'A': { order: 1, g ...

Angular: Activate async validator for form group only when all controls have values

Is there a way to trigger validation for FormGroup only after all the fields in the group have been filled out, instead of triggering it every time a field is filled? ...

Is it possible for me to change a selector value?

Currently, I am working on an app that utilizes NGRX. I have a question regarding the store being a readonly place where direct object mutation is not allowed. However, I am unsure about the use of selectors. For example, consider the following NGRX sele ...

Interface of TypeScript Undetermined

Currently, I am developing a Demo API Wrapper specifically for Roblox. During the development process, I have come across a certain issue that I would like to address. My aim is to send a request and then return all the data in the manner of an API wrapper ...