Adjust the selected value in real-time using TypeScript

Hey there, I've got a piece of code that needs some tweaking:

<div>
    <div *ngIf="!showInfo">
      <div>
          <br>    
<table style="border: 0px; display: table; margin-right: auto; margin-left: auto; width: 155%;">
                <tbody>
                  <tr>
                    <th style="color: black;border: 0px;">Type</th>
                    <th style="color: black;border: 0px;">Radius</th>
                    <th style="color: black;border: 0px;">Number</th>
                  </tr>
                  <br>
                  <tr *ngFor="let row of groups;let i = index">
                    <td style=" border: 0px;" >
                      <input #focus matInput type='text' style=" border: 0px;"  type="text" value="{{row.type}}" readonly  [(ngModel)]="row.type" >
                    </td>
                    <td>
                      <select (change)="changeRadius($event, i)" attr.id="{{row.id}}" [value]="5000">
                        <option *ngFor="let meters of radius"  [value]="meters.value">{{meters.value}}</option>
                      </select>
                    </td>
                    <td style="margin-left: 60px; border: 0px;">
                      <input  matInput type='text' style="margin-left: 30px; border: 0px;" readonly  type="text" value="{{row.number}}" [(ngModel)]="row.number">
                    </td>
                  </tr>
                </tbody>
              </table>
            <hr style="color: darkred;" >

            <div>
              <button mat-button class="custom-button" (click)="getNewRadius()">
                  OK
              </button> 

The first time this table is displayed, I want each select to default to 5000. Then the user can choose a new radius for each select and click OK. In my TypeScript file, I have an array called "radiousToSend" that stores the selected radii. Now, whenever this table reappears, I want the selects to default to the last chosen radius from "radiousToSend."

I attempted to achieve this with the following code snippet:

let pan = (<HTMLInputElement>document.getElementById('1'));
    pan[0].options[pan[0].options.selectedIndex].selected = true;

Unfortunately, it didn't work as expected because every time the table appears, all the selects default back to 5000. I only want them to stay static the very first time.

Answer №1

To establish a connection between the view and controller, you have the option to utilize two-way binding by employing the ngModel directive.

Example Template:

<select (change)="changeRadius($event, i)" attr.id="{{row.id}}" [(ngModel)]="selectOption">
  <option *ngFor="let meters of radius" [value]="meters.value">{{meters.value}}</option>
</select>

Ensure to modify the value of the variable selectOption in the click event handler logic.

Controller Section:

export class AppComponent  {
  selectOption = 5000;   // Default value set for all select options

  getNewRadius() {    // Update all options to 1000 when the button is clicked
    this.selectOption = 1000;
  }
}

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

The function is trying to access a property called addclass on an object

When I pass a dom node along with a classname to a directive, the directive should add a class to the passed dom element. However, I am encountering an error that says "Cannot read property addclass of undefined." For reference, please visit this plnkr l ...

I'm curious as to why I am receiving an empty array as a response when I send a post request to the API

I am experiencing an issue while sending data to an API using a post method. I have structured the data in an object as per the server's requirements, but upon posting the object to the API, I receive a response with a status of 200 and an empty array ...

Reversing ngModel modifications does not accurately display changes in the view

Presently, my table contains editable cells, with the functionality to undo changes to each cell. To achieve this, I initially created a duplicate of each object in the array. Upon initialization, I mapped the array to create a new array with old values s ...

Whoops! Looks like there was a hiccup with the Vercel Deployment Edge Function, causing an

Every time I attempt to send a POST request to my Edge Function on Vercel Deployment, I encounter the following error message: [POST] /api/openai reason=EDGE_FUNCTION_INVOCATION_FAILED, status=500, user_error=true TypeError: Illegal invocation at app/api/ ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...

JavaScript/Typescript is throwing an error because it is unable to access the property 'username' of an undefined object

In my project, I am attempting to compile a list of Profile objects and then extract specific elements from each object in the list. To accomplish this, I have defined a public interface named Profile, imported it into my component, and instantiated a new ...

Every row within the data grid component must contain a distinct `id` property

How do I utilize statId instead of id in my code? Should I create a unique id property for each row? Error: MUI: All rows in the data grid component must have a distinct id property. Alternatively, you can define a custom id using the getRowId prop. A ...

Karma's connection was lost due to a lack of communication within 10000 milliseconds

The Karma test suite is encountering issues with the following message: Disconnected, because no message in 10000 ms. The tests are not running properly. "@angular/core": "7.1.3", "jasmine-core": "3.3.0", "karma-jasmine": "1.1.2", The failure seems t ...

What could be the reason behind tsx excluding attribute names with "-" in them from being checked?

Why doesn't TypeScript check attributes with a hyphen in the name? declare namespace JSX { interface ElementAttributesProperty { props:any; // specify the property name to use } } class A{ props!:{p1:string} } const tsx = <A p1="&q ...

"Within Angular 2+, the attribute referenced is not recognized as a valid property, even though it is explicitly defined within the @Input

The main goal here is to increase the vertical pixel count. <spacer [height]="200"></spacer> Initially facing an issue where an error message states that height is not a recognized attribute of spacer. To address this problem, I set up the fo ...

Is there a way to verify the presence of data returned by an API?

I am trying to implement a system in my Index.vue where I need to check if my API request returns any data from the fetchData function. Once the data is fetched, I want to return either a boolean value or something else to my Index.vue. Additionally, I wou ...

Utilizing Angular to lazily load multiple routes/paths within a single module

I am currently in the process of setting up multiple horizontal routes (not nested) and grouping them into one lazy-loaded module. However, I am facing a challenge trying to properly match these routes within the lazy-loaded feature module itself. Below ...

In TypeScript, Firestore withConverter may return a QueryDocumentSnapshot instead of the expected Class object

I'm currently exploring the usage of Firestore's withConverted method in Typescript to retrieve queries as instances of my customized class. Custom EventConverter Class import Event from "@/models/Event"; class EventConverter implemen ...

The absence of certain attributes in TypeScript

class DeploymentManager { import { observable, action, makeAutoObservable } from "mobx" public deploymentQueue = observable<IDeploymentProject>([]); public inProgressProjects = observable<IDeploymentProject>[]; public s ...

Troubles arise when trying to compile Typescript and React with esbuild

I set out to create a new package and upload it to npm, starting with a demo package first. I began by using this repository as a foundation: https://github.com/wobsoriano/vite-react-tailwind-starter After that, I made updates to the build script: " ...

Issue encountered with JavaScript function within TypeScript file connected to HTML code

I am currently working on a simple SharePoint web part and encountering an issue with using a function from another module file in my main file. Snippet from the JSFunctions.module.js file (where I define my function): function getApi(){ [my code]... }; ...

The logout feature might refresh the page, yet the user remains logged in

Currently, I am enrolled in a course on Udemy where the instructor is utilizing Angular 2. My task involves building the app using the latest version of Angular. The issue that I am facing pertains to the logout functionality. After successfully logging ou ...

Even though there is data stored in the array, the React Native array.length appears to be returning a value

I am struggling with what appears to be a simple issue, and it's frustrating that I've had to seek help for this. The problem lies in iterating through an array messages: Message[] = [...]. No matter what method of iteration I try, it doesn&apos ...

Tips for showcasing an array in nested elements within an Angular mat-tree

I'm new to Angular and I need help displaying an array's values within the child elements of a material tree. Specifically, I want to show the names of fruits (such as Apple, Banana...) in the child elements. The colors and discounts from the ar ...

Navigating Angular: Uncover the Secrets of Unwrapping Json Data

I need some help with parsing Json data in Angular TypeScript. The data is structured as follows: https://i.sstatic.net/H7s8q.png When calling a REST API, I want to convert a Java class object into an array of model classes. How can this be achieved? "g ...