Prevent selection based on function in Angular

I'm attempting to prevent certain options from being selected based on a specific method.

For instance, let's say I have four options:

A
B
C
D

In my method (let's use "x" as an example):

if(name == A) {
disable the selection for option A.
}

This is my code:

this.http.getDataFromServer("api/....).subscribe((resp) => {
  
  this.code = resp.data["route"];
  console.log(this.code);
});

Within this.code, there are multiple sets of data. The corresponding HTML in the component looks like this:

            <div class="form-group">
                <label for="route_code">
                    Route Code
                </label>
                <select type="text" class="form-control" formControlName="route_code" (change)="codeSelected($event.target.value)">

               <option [value]="r.id"  *ngFor="let r of code" [disabled]="disable()">
                        {{r.code}}
                    </option>
                </select>
            </div>

Here, r.code represents the available options in the dropdown list.

After doing some research, I came across the [disable] attribute, which can be assigned to a method named disable().

The component.ts file contains the following code:

disable(){
}

What should I include within the disable() method? For example, if I want to disable an option when r.code == "A", could you please assist me?

Answer №1

A potential approach could involve passing the disable value as an argument:

widget.html

<div class="form-group">
    <label for="route_code">
        Route Code
    </label>
    <select type="text" class="form-control" formControlName="route_code" (change)="disableSelection($event.target.value)">
        <option [value]="";
r_id "=" * ngFor = "let r of code"[disabled]="checkAvailability(r.code)">
            {{ r.code }}
         </ option & gt;
    & lt;/ select & gt;
</ div & gt;

widget.ts

checkAvailability(code: string): boolean {
  return code === "B";
}

Answer №2

To incorporate the current x into your function, utilize this approach:

<option [value]="x.id"  *ngFor="let x of data" [disabled]="disable(x)">
        {{x.dataValue}}
</option>

Then, in the disable method, you can access and manipulate the value that was passed in:

function disable(x) {
   return x.dataValue === "A";
}

This will yield either true or false.

Expect positive results from this solution.

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

Creating a Seamless Bond Between JavaScript and HTML

I've been struggling to find a helpful and straightforward solution to a simple problem. On my web page, I have five image placeholders that should be filled with one of nine random pictures. To achieve this, I wrote a JavaScript code that generates r ...

Ember's distinctive feature: Named Block Helpers

Can we create "named blocks" in a different way? For instance, {{#customBlock "repeatableBlock"}} {{!-- block containing numerous properties and data that may become messy if hardcoded multiple times --}} {{/customBlock}} Then, elsewhere in the code, {{ ...

Angular: Transforming input types

When the div is pressed, it triggers a function that changes the type of input. There are two password inputs that are changed to text when the function is triggered. Issue Error 1: 'password' may be null. If I enter '' in the password ...

"Repeating SignalR Messages: Issue of Duplication when Stopping and Restarting

Whenever I stop and start the connection, messages sent to the client by the hub are duplicated. If I follow this sequence: $.connection.hub.stop() $.connection.hub.start() {...} and a message is sent from the server hub to the client, it is initially re ...

Get the application/pdf document that was just sent to you from the software backend

I am facing an issue with downloading a PDF file sent from the backend. Upon receiving a blob response, I notice that when I download and view the file, the sheets are empty, matching the expected number of sheets. Could this be a coding problem? Current ...

Backand - How can I display the contents of variables using console.log() within Security Actions?

Is there a way to utilize console.log() in Backand, specifically within the server side functions like those found under Security & Auth > Security Actions? I have checked the Read.me which suggests using 'console.log(object) and console.error(object) ...

Instructions for removing the status bar from the configuration file

Struggling to remove the status bar that's covering my header in my Phonegap-wrapped HTML5 mobile app. I've tried adding preferences to the config.xml file, but still no luck. Here's what I added: <preference name="fullscreen" value="tr ...

Node and Express Fundamentals: Delivering Static Resources

const express = require('express'); const app = express(); app.use(express.static('public')); I've been attempting to complete the "Basic Node and Express: Serve Static Assets" challenge on freecodecamp, but it keeps showing as " ...

Mysterious anomaly observed: Peculiar trajectory detected in canvas image during left

I have a fascinating HTML5 Canvas that showcases the movement of two identical objects to both the right and the left. Although the right side operates flawlessly, I've noticed that the left object leaves behind an intriguing trail with a hint of gree ...

A single click is required for Observables to load on an HTML page

While working on my Angular web application, I encountered an issue with displaying data when using Observables and Subjects. Typically, when searching the Firebase DB, I use *ngFor="let myvar of _myvar | async" in my HTML to display the retrieve ...

Queueing up file downloads through a web browser

When trying to download multiple files from a server, I am required to queue them up instead of downloading in parallel. Unfortunately, I do not have access to the download server, so my only option is to work with the browser. Is there an API available t ...

Establishing a user session with Node.js

I am new to the world of node.js and JavaScript in general. I have a piece of code that currently handles login functionality by checking if a user exists in a MYSQL database. This part is functioning correctly. Now, I wish to improve this feature by crea ...

Troubleshooting Issue with Internet Explorer failing to update Asp.Net MVC3 Partial View

I am experiencing an issue with a page that includes a div for a partial view loaded via an ajax request. $.ajax({ url: 'CompleteSessions', success: function (data) { var selector = $('#complete-session-sect ...

Creating distinct identifiers for table cells utilizing the map function

Is there a way to assign a unique id to each MenuItem using the map() function nested within another one? <table className={classes.table}> <thead> <tr> <td /> {sit.sit.map(sit => ( <td className={ ...

Highlight particular terms (key phrases) within text contained in a <td> tag

I am currently working on a project and facing a challenge that I am unfamiliar with. My task is to highlight specific keywords within text located inside a <td> element. I cannot manually highlight the keywords as the texts are dynamic, originating ...

Error encountered when trying to load Ajax script

As a beginner in the learning process, my code may appear messy. I am currently wrapping up my second project, which is a photo viewer. On the main page, there is a navigation system that loads different sections of the website using ajax. Since this proje ...

Is it more efficient to define a variable or call a method from an object?

Which approach is more effective and why? Option 1: Declaring a variable exampleFunction(requestData: Object) { const username = requestData.username; doSomething(username); } Option 2: Accessing the object property directly exampleFunction(reques ...

Tips for managing your time while anticipating an observable that may or may not

I am facing a dilemma in my Angular app where I need to conditionally make an HTTP call to check for the existence of a user. Depending on the result of this call, I may need to either proceed with another API request or halt the processing altogether. I ...

Validate fields by iterating through an object and considering three data points for each field

The struggle is real when it comes to coming up with a title for this question. Suggestions are welcomed! When it comes to field validation, I require three data elements per field: variable name, element ID, and whether it is required or not. Although I ...

Developing in Angular 2: Enhancing JSON data before passing it to the template

After receiving data from a JSON source, I have the following: { "name": "Leonardo", "weapon": "sword" }, { "name": "Donatello", "weapon": "stick" }, { "name": "Michelangelo", "weapon": "nunchucks" }, { "name": "Raphael", " ...