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

Unable to employ a custom Typescript .d.ts file

Currently, I am delving into learning TypeScript and encountering a hurdle while attempting to define a class in a TypeScript definition file and then utilize it in a TypeScript file. The dilemma lies with a JavaScript "class" called "Facade," which serve ...

What is a creative way to design a mat-radio-group without traditional radio buttons?

I am looking to create a component that offers users a list of selections with the ability to make only one choice at a time. The mat-radio-group functionality seems to be the best fit for this, but I prefer not to display the actual radio button next to t ...

Utilize the provider within the decorator function

Essentially, the challenge I am facing is passing an authService to the "verifyClient" function within the @WebSocketGateway decorator. Here is how it should look: @WebSocketGateway({ transports: ['websocket'], verifyClient: (info: { req: Inc ...

Accessing Webpack bundles using an "@" symbol for imports

I am currently working on bundling a Node Express server that was created using TypeScript and is being packaged with Webpack. Everything seems to be running smoothly when I compile/transpile the code into one JavaScript file called server.js. However, af ...

A guide on implementing Angular-DataTable within a TypeScript project

Hey everyone, I'm currently working on a TypeScript and Angular application. To create a data table, I decided to use Angular-DataTable. After creating a sample application using it, I added the following code to my Controller: constructor(protecte ...

Problem Encountered with Inaccurate Binding of Dynamic Form Control Values in Angular

UPDATE: Follow this link to access the editor for my Stackblitz application, which demonstrates a simplified version of the issue regarding the "transfer" of value between the first and second controls. I am currently developing a dynamic form in Angular ...

Can the detectChanges() method in Angular cause any issues when used with the form control's valueChanges event?

Within my parent Component, I am working with a formGroup and updating its value using patchValue method. ngAfterViewInit() { this.sampleform.controls['a'].patchValue ...} I then pass this form to a child component in the parent component's ...

Updating the value of a variable in a separate file with Node.js

I'm facing a business scenario that can be likened to a challenging situation. To simplify, here's the problem: File1.ts import * from 'something'; export const var1="value of var1"; //assume there is a variable 'x' ...

Autocomplete search from a distance

I am currently learning Angular and trying to create an autocomplete form with content that is filtered on the back-end. I have defined a class and Interface for Terminal: export class Terminal { constructor( public id: number, public name: ...

The REST API seems to be functioning correctly when accessed through Postman, but there are issues when attempting to call

When I include @PreAuthorize("hasRole('ROLE_SUPER_ADMIN')") in my controller and make a call from Angular, it doesn't work. However, it works fine when called from Postman. @GetMapping("/getAllOrgniz") @PreAuthorize("hasRole('ROLE_SUPE ...

After compiling the code, a mysterious TypeScript error pops up out of nowhere, despite no errors being

Currently, I am delving into the world of TypeScript and below you can find the code that I have been working on: const addNumbers = (a: number, b: number) => { return a + b } Before compiling the file using the command -> tsc index.ts, the ...

Solving the 'never' type issue in Vue3 and TypeScript for an empty array reference

I am currently in the process of migrating a component from an old Vue project that relies solely on JavaScript to a TypeScript/Vue project, and I have encountered some obstacles along the way. <script lang="ts"> import { computed, ref } fr ...

Visibility in classes can shift once a new file is imported

Currently, I am encountering a puzzling issue in my angular2 project using typescript. In my main.ts file, which contains a component along with some imports at the start of the file, there is a custom type class (let's call it TypeFoo) located in mod ...

Updating text inputs in Angular can be done more efficiently using Angular Update

I need to make adjustments to an Angular application so that it can run smoothly on older machines. Is there a more efficient method for updating a text input field without using (keyup) to update after each keystroke? I haven't been able to find any ...

Discovering the process of reaching service members through an HTML View

Currently, I am in the process of learning Angular 2 and find myself unsure about the most efficient way to update the view. For instance, let's say I have two components: User and Main. The User component retrieves a list of users from the UserServ ...

What is the best way to restrict the number of iterations in ngFor within Angular HTML

I want to use ngFor to display a maximum of 4 items, but if the data is less than 4, I need to repeat the loop until there are a total of 4 items. Check out this example <img *ngFor="let item of [1,2,3,4]" src="assets/images/no-image.jpg" styl ...

The Angular elements encountered a problem when trying to create the 'HTMLElement'. The construction failed

I am experimenting with a simple Angular elements application on StackBlitz and encountering the following problem. Error: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be call ...

Modification of encapsulated class in Angular is not permitted

Within Angular, a div element with the class "container" is automatically created and inserted into my component's HTML. Is there a way to modify this class to "container-fluid"? I understand that Angular utilizes encapsulation, but I am unsure of how ...

Commit to choosing an option from a dropdown menu using TypeScript

I just started learning about typescript and I have been trying to create a promise that will select options from a drop down based on text input. However, my current approach doesn't seem to be working as expected: case 'SelectFromList': ...

NGXS State Mutation Event

In my NGXS store, I have an object called obj = { name: 'so-and-so', age: 42, nationality: 'country-name', address: { ... } }. It is essential that whenever any of the properties, including nested ones like 'address', are upda ...