A step-by-step guide on assigning values to an Angular Material Auto Complete component in Angular 7

Hey there! I'm currently using the Angular Material Auto complete component in my Angular 7 app and I'm trying to find a way to bind a value from an API response to it. Can someone help me out with a solution for this?

HTML:

<mat-form-field>
    <input type="text" [(ngModel)]="templateId" name="templateId" #templateId="ngModel" placeholder="Template" matInput
        [matAutocomplete]="auto" aria-label="Number" (keyup)="filter($event)">
    <mat-autocomplete #auto="matAutocomplete" (optionSelected)="onTemplateChange($event)">
        <mat-option *ngFor="let temp of filtered" [value]="temp">
            {{temp.name}}
        </mat-option>
    </mat-autocomplete>
</mat-form-field>

Ts:

onTripTemplateChange($event) {
        this.templateId = $event.temp.name;
}
  1. I want the value to be selected by default when I open the component
  2. When I change the option from the auto complete list, I need to update the selected value

If you have a solution, please share it with me!

Answer №1

According to the original documentation on angular material autocomplete, it is necessary to set the value for the autocomplete by also setting the value for the input element.

You can find the complete documentation here:

An example of this functionality can be seen in the sample app available on stackblitz: https://stackblitz.com/angular/egaebogmkaa?file=src%2Fapp%2Fautocomplete-simple-example.ts

The provided sample app demonstrates a basic autocomplete scenario, where setting a value for the input in the .ts file will automatically select it. For instance:

 myControl = new FormControl('One');

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

Is it more efficient for the component to retrieve data from storage or to be provided with the data

Within my Angular application (version 10), I utilize data that is unique to each request. To make certain business decisions, I extract information from a portion of the URL domain name. In the early stages of development of my application, I extracted t ...

The Vuex MutationAction decorator cannot be assigned to a TypedPropertyDescriptor

I am a beginner in Typescript and apologize in advance if this is a rookie mistake. I am struggling to resolve this TS error: @Module({ namespaced: true, name: "Admin" }) class Admin extends VuexModule { public adminUserList: UserList = []; ...

Attempting to start an Angular project using NG NEW constantly fails nowadays - always ends with error code EPERM

Can Angular still be considered a reliable framework when pervasive errors and bugs persist for extended periods without any clear resolution documented? .... 24695 silly saveTree | +-- <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Adjusting a variable's value based on the changes of another variable

In the process of developing an application feature for managing favorites, I am integrating data from two different sources. One source is a const file that I am exporting as an observer (observerA$), while the other source is a database containing only t ...

Exploring nested grandchildren components in Angular2 Dart

Currently, I am attempting to make the following code work in Angular2 Dart: <div class='test'> <accordion2> <accordion-item-2 title="blah" active="true"> <sample-form-1></sample ...

Updating Checkbox Appearance in Angular 6 Based on its Checked Status

I have created a checkbox list and I am trying to style the checked item with an underline. Here is my code snippet: TS file: currentQuarter: string; quarters: Observable<MeseRiferimento[]>; q1: MeseRiferimento = new MeseRiferimento(); q2: MeseRife ...

Guide on how to access the key of an object within the ngx-bootstrap typeahead feature?

When creating a custom component that utilizes ngx-bootstrap's Typeahead feature, the documentation indicates the ability to specify which item of an object can be searched for. If I have a list of key-value objects, how can I search for the value and ...

Executing TypeScript Mocha test cases using ES6 modules

Setting up mocha tests for the TypeScript App in my Rails application has been a bit of a challenge. Initially, I added a basic test to kick things off, but encountered the following error: /home/bernhard/Programs/ruby/cube_trainer/jstests/utils/optional. ...

Fastify Schema Failing to Validate Incoming Requests

Currently, our backend setup involves using Node.js and the Fastify framework. We have implemented a schema in satisfy to validate user input. Below is the schema defined in schema.ts: export const profileSchema = { type: 'object', properti ...

The type 'string' cannot be assigned to the type '"GET" | "get" | ...'

In my custom hook, I utilize the axios library for making requests: const useCustomHook = ({ endPoint = "", method = "GET", options = {} }) => { const [data, setData] = useState([]); const [request, setRequest] = useState<AxiosRequestConfig> ...

Combine objects by selecting attributes from multiple objects

declare type A = {type: 'TypeA', attr1: string} declare type B = {type: 'TypeB', attr2: string} declare type U = A | B When I use type X = Pick<U, 'type'>, I get: { type: 'TypeA' | 'TypeB' } But I a ...

The Angular template driven forms are flagging as invalid despite the regExp being a match

My input looks like this: <div class="form-group"> <label for="power">Hero Power</label> <input [(ngModel)]="model.powerNumber" name="powerNumber" type="text" class="form-control" pattern="^[0-9]+$"id= ...

Pass a personalized header during preflight request OPTIONS in angular version 5

I have recently developed an Angular 5 app that communicates with a REST API built using Golang and hosted on an AWS EC2 instance running on port 8080. When my angular front-end code sends a POST request, the browser initiates a CORS preflight request, but ...

Troubleshooting: Angular add/edit form issue with retrieving data from a Span element within an ngFor loop

I am currently working on an add/edit screen that requires submitting a list, among other data. The user will need to check 2-3 checkboxes for this specific data, and the saved record will have multiple options mapped. Here is what the HTML looks like: &l ...

Launching Angular 7 on github pages

I am facing an issue with my Angular 7 app that features two routes: the main route and the 'article' route. While the app functions perfectly when tested locally, it fails to load the page's css when deployed on GitHub pages. I followed the ...

"Utilize a loop in Angular 2 to consistently send HTTP GET requests to service

Hello, I'm new to working with Angular. Currently, I have an array of product IDs and I would like to make HTTP GET requests based on each ID in the array using a loop. Can someone assist me with this task? Service : addedProductIdArray : string[] = ...

Utilizing ngx-logger Dependency in Angular 6 for Efficient Unit Testing

Have you ever attempted to test classes in Angular that rely on ngx-logger as a dependency? I am looking for guidance or examples of how this can be achieved using testing frameworks such as Jasmine. It seems there are limited resources available on mock ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...

Displaying an Array in HTML using Angular

Just starting out with Angular and experimenting with data display from an array. The data in the array is: [Me, Three, Four] I attempted to loop through it for printing but encountered issues. Here's a snippet of how I'm currently handling it: ...

What could be causing maven install to throw an error in relation to npm?

After merging two branches, an error occurred: [ERROR] The goal com.github.eirslett:frontend-maven-plugin:1.6:install-node-and-npm (install node and npm) on project frontend failed to execute because it couldn't extract the npm archive located at & ...