Determining whether an option value has been selected in Angular

I am working on a template that includes mat-autocomplete for element searching, with individual option elements displayed. I am trying to implement logic where if an element is selected, the input should be disabled. How can I determine if a specific element has been selected in mat-autocomplete?

HTML

<input [matAutocomplete]="auto" matInput formControlName="targetListValue">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
   <mat-option *ngFor="let targetItem of filteredTargetListOptions" [value]="targetItem">
     {{targetItem.value}}
   </mat-option>
</mat-autocomplete>

Typescript

ifSelectedItem() {
 if (// check if option has been selected) {
   this.form.controls.targetListValue.disable();
 }
}

Answer №1

As stated in the documentation at this link, MatAutoComplete includes an output called optionSelected. To implement this feature, I recommend trying the code snippet below:

<input [matAutocomplete]="auto" matInput formControlName="targetListValue">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)="ifSelectedItem()">
   <mat-option *ngFor="let targetItem of filteredTargetListOptions" [value]="targetItem">
     {{targetItem.value}}
   </mat-option>
</mat-autocomplete>

Answer №2

Programming with Typescript

checkIfOptionIsSelected(event: any) {
   const optionValue = event.option.value
   if (optionValue) {
     this.form.controls.targetListValue.disable();
   }
}

Creating HTML Elements

<mat-autocomplete (optionSelected)="checkIfOptionIsSelected($event)" 
                  [displayWith]="displayFn"
                  #auto="matAutocomplete"
>
    // list of options
</mat-autocomplete>

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

What is the reason behind document.body not being recognized as an HTMLBodyElement?

Why does Visual Studio suggest that document.body is an HTMLElement instead of an HTMLBodyElement? I've searched for an answer without success. class Test { documentBody1: HTMLBodyElement; documentBody2: HTMLElement; cons ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

Using a dictionary of class types as input and returning a dictionary of their corresponding instances

Is there a way to create a function that takes a dictionary with class values as an argument and returns a dictionary of their instances? For example: classes C1, C2 function f: ({ name1: C1, name2: C2 }): ({ name1: new C1() name2: new C2 ...

How can you adjust the size of focused elements like autocomplete or datepicker in Angular Material 15?

I recently updated to Material 15 and I'm wondering how I can adjust the height or overall size of focused components like autocomplete or datepicker. The page mentioned that density cannot be used on such components, so what other methods are availa ...

Having trouble getting Angular's ngClass directive to work correctly when applying multiple conditions

Struggling to make multiple conditions work with [ngClass] Check out a.component.html <div class="version-content" *ngFor="let version of versions; let lastVersion = last" [ngClass]="(version.isComingSoon === true) ? 'dashed': 'solid"> ...

Set up the hardware back button to respond to the current route condition in Ionic 4

Upon launching my Ionic4 application, users are directed to a login page where they can input their credentials. Once logged in successfully, they are redirected to the tabbed interface ion-tabs. The login URL is set to localhost:8100/#/login. The reques ...

A guide on managing Ngb Bootstrap carousel slide with a button in Angular

I encountered a situation like this: I need to implement a Ngb Bootstrap carousel with buttons for Previous and Next to control the slide images. Clicking on the Previous button should display the previous slide image, and clicking on the Next button shou ...

Gridster2 for Angular: Resolving Overlapping Grid Items during Drag

The Angular version being used is 4.0.0 The angular-gridster2 library version being used is 2.10.0 When dragging the items randomly over other items, they become overlapped (as shown in the image below) The circled numbers represent the number of column ...

How to Generate a Unique URL in Angular 7 Using Typescript

I'm struggling to display or download a .pdf file in my Angular 7 project due to issues with window.URL.createObjectURL. Here's the code snippet I've written: this.userService.getFile(report.id).subscribe( res => { console.log(res) ...

I'm facing difficulty in assigning props because of the specific nature of generics in Typescript

My goal is to create a Higher Order Component (HOC) that can control a component which relies on certain props to function properly. To elaborate: I want to build a HOC that takes a component expecting props value and onChange, and modifies it so that the ...

The mat-select element is defaulting to the last value in a loop for all dropdown selections

I am working with a Mat-select tag that is inside a loop using *ngFor, and by default, it is selecting the last value for all dropdowns. <div *ngFor="let investment of data.priorInvestmentExperiences; > <mat-form-field appearance="outline" ...

Using Tailwind @apply within an Angular application's CSS file

I've noticed a yellow line appearing under the @apply in my CSS files, even though the styles are being applied correctly to the HTML components. This seems to be happening in every CSS file I use. Can anyone shed light on this issue? Removing these ...

Angular functions are executed twice upon being invoked within the html file

I decided to kick-start an Angular project, and I began by creating a simple component. However, I encountered a perplexing issue. Every time I call a function in the HTML file from the TypeScript file, it runs twice. TS: import { Component, OnInit } from ...

I am facing an issue where I am unable to retrieve a static variable from a global component within a subscribed component in Angular 7

I keep encountering an undefined variable issue when inside the subscribe function. import { AppSetting } from '../config/app-setting'; this.api.userLogin(this.loginForm.value.emailid,this.loginForm.value.password).subscribe( data => { ...

The where clause in the Typeorm query builder instance is not functioning properly after its common usage

When fetching data for my relations, I opted to use QueryBuilder. In order to validate certain get request parameters before the index, I established a common QueryBuilder instance as shown below. // Common Get Query const result = await this.reserva ...

Angular 6 Time Discrepancy

I am trying to display real-time time difference on the UI that updates every second. Here is what I have attempted: component.ts import { Component, OnInit } from '@angular/core'; import 'rxjs/add/observable/of'; import 'rxjs/a ...

Using Angular/Typescript to interact with HTML5 Input type Date on Firefox (FF)

Are there any Angular/Typescript projects that are completely built without relying on third-party libraries? I am encountering problems with Firefox and IE11. It works fine on Chrome where the value can be read, but the calendar does not display when us ...

Error message in TypeScript: A dynamic property name must be a valid type such as 'string', 'number', 'symbol', or 'any'

Attempting to utilize the computer property name feature in my TypeScript code: import {camelCase} from "lodash"; const camelizeKeys = (obj:any):any => { if (Array.isArray(obj)) { return obj.map(v => camelizeKeys(v)); } else if (ob ...

"Learn how to utilize array values in TypeScript to easily display them using NgFor in HTML

Looking for a solution: <select (change)="getYear(year)"> <option value="year" *ngFor="let var of array; let i = index" {{year.year}} </option> </select> Is there a way to configure the typescript code so that I can dynamica ...

The Child Component encountered difficulties in connecting to the EventEmitter via the service

In the code snippet below, we have the Subscribing Component "pop-list.component.ts" : import { Component, OnInit } from '@angular/core'; import { ChildCommService } from '../child-comm.service'; @Component({ selector: 'app-pop- ...