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

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

What is the role of the "prepare" function in AWS CDK constructs?

TL;DR: What is the role and purpose of the prepare(): void method in AWS CDK's Construct class? When and how should it be utilized or avoided? The information provided about prepare() states: prepare() function is called after child constructs have ...

Struggling to grasp how to implement Redux and React-router together in one component

I have recently embarked on learning TypeScript and encountered a confusing behavior. Upon encountering this error: Type 'ComponentClass<{}>' is not assignable to type 'StatelessComponent<void | RouteComponentProps<any>> ...

Issue with Ng test: The type definition file for '@angular/localize' cannot be located

When upgrading from Angular 14 to 17, I ran into an issue with the ng test command. It seems to be malfunctioning now. Error: PS C:\ForAngular17\src\ng\cat-ng> ng test One or more browsers configured in the project's Browsersli ...

Is there a way to change the data type of all parameters in a function to a specific type?

I recently created a clamp function to restrict values within a specified range. (I'm sure most of you are familiar with what a clamp function does) Here is the function I came up with (using TS) function clamp(value: number, min: number, max: number ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

The JSON object, which has been converted into a string and sent over the network,

Attempting to set up a websocket server using TypeScript in Node.js, the following code was used: ws.on('message', (msg: string) => { console.log("got message:" + msg); const m = JSON.parse(msg); console.log(m); ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

Mastering the art of shaping state in NGRX for the master-detail pattern

Imagine a scenario where I am developing a compact app for organizing tasks. This app makes use of angular and NGRX to efficiently manage the state. Each day, the user loads tasks in the morning and then travels to different locations to complete them. Th ...

Discover how Angular 8 allows you to access a method result from a child component in the parent component using ViewChild once the method has been called in the

In my child component, I have implemented two buttons as shown below: child-component.html <div> <button (click)="getFirstData()">First</button> <button (click)="getLastData()" >Last</button> </div> In child-com ...

Utilizing WebPack 5 in conjunction with Web workers in a React/Typescript environment

Can someone help me figure out how to make a web worker function properly with create-react-app, Typescript, and Webpack 5? I've been struggling with limited documentation and can't seem to find a clear explanation. I'm trying to avoid using ...

Encountering the error "Element implicitly has an 'any' type because expression of type 'string' cannot be used to index type '{}'" can be frustrating when working with React TypeScript

I'm encountering an issue when trying to access an object with an id in the code below. An error message stating 'Element implicitly has an 'any' type because expression of type 'string' can't be used to index type ' ...

What is the best way to emphasize when the path matches exactly with '/'?

Is there a way to highlight the path only when it exactly matches '/'? Currently, even on 'Page 2', the 'Home' link is still highlighted. Check out the plunker here .active { color: red; } <a routerLinkActive="active" r ...

Utilize Angular 2 to search and filter information within a component by inputting a search term from another component

In my application, I have a Component named task-board which contains a table as shown below: <tr *ngFor="let task of tasks | taskFilter: searchText" > <td>{{ task.taskName }}</td> <td>{{ task.location }}</td> <td>{{ ta ...

TypeScript causing issues when multiple selectors are used

Currently, I have a function that allows me to search for HTML elements based on text content: function findElementsByText(text: string): HTMLElement[] { const selectors = 'button' // This conditional statement ensures that an empty text quer ...

Issue with routing in a bundled Angular 2 project using webpack

Having a simple Angular application with two components (AppComponent and tester) webpacked into a single app.bundle.js file, I encountered an issue with routing after bundling. Despite trying various online solutions, the routing feature still does not wo ...

AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application. My app is a brand new Angular cli project following the mentioned guide. My objective is to utilize the standalone auth components a ...

Having trouble with Angular 2 Routing and loading components?

I am facing an issue with Angular 2 where it is searching for my component in app/app/aboutus.component, but I cannot pinpoint the source of the problem. Here is my app.component.ts code: import { Component } from '@angular/core'; import { ROUT ...

Eureka - Spring Cloud Services: Discover the Benefits

Currently, I am diving into the world of microservices with Spring and Spring Boot, looking to deploy my work onto a cloud platform. My goal is to develop an Angular 2 frontend application that interacts with my deployed microservice. Right now, I am exp ...

Exploring Angular Route Configurations: Utilizing Multiple Outlets with Path as an Array of

In my Angular9 application, I have configured hundreds of routes paths. Is there a way to use multiple outlets with a single array of string paths? Current Code: const routes: Routes = [ { path: 'Data/:EntityID/:Date', compon ...