Enhancing the selection of options in Angular 2 using object values

When I retrieve a list of object values from an API, each object contains a property to identify the selected item. I am successfully binding the items list to the view.

Here is the JSON data:

https://i.sstatic.net/itmfh.png

Below is my code snippet:

<select class="form-control" name="Underwriter">
  <option *ngFor="let underwriter of policyModel?.underwriterList" [ngValue]="underwriter.value">{{underwriter.text}}</option>
</select>

Is there any way to ensure that the selected item is displayed properly?

Answer №1

To determine which underwriter has property selected set to true, simply add [selected] to your select element.

Here is an example:

<select class="form-control" (change)="onChangeUnderwriter($event)" name="Underwriter">
     <option *ngFor="let underwriter of policyModel?.underwriterList" [ngValue]="underwriter.value" [selected]="underwriter.selected == true">{{underwriter.text}}</option>
</select>

Therefore, include the following line:

[selected]="underwriter.selected == true"

View a simplified version on Plunker

Answer №2

When looking to "make" the selected item, it is commonly understood as setting it. Here is one way to achieve this, although there may be alternative methods.

To set the [attr.selected] in the option tag:

<select class="form-control" name="Underwriter">
 <option *ngFor="let underwriter of policyModel?.underwriterList" [ngValue]="underwriter.value" [attr.selected]="underwriter.text === underwriterTextString ? true : null">{{underwriter.text}}</option>
  </select>

In your code, ensure that you assign a value to underwriterTextString when the WebService API provides a response.

If underwriter.text does not yield the desired results, consider using underwriter.value.

However, if your objective now is to "get" the selected item, you can utilize the change event within the select tag:

<select class="form-control" (change)="onChangeunderwriter($event)" name="Underwriter">
     <option *ngFor="let underwriter of policyModel?.underwriterList" [ngValue]="underwriter.value" [attr.selected]="underwriter.text === underwriterTextString ? true : null">{{underwriter.text}}</option>
      </select>

Your code should include something like this:

onChangeunderwriter(event) {
//the value will be set in event.target.value;
}

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

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

Replacing the '+' character with a space in HttpParams within Angular 6

When passing a JSON object using HttpParams, the + character is automatically converted to a space before being sent to the backend. Despite trying multiple solutions, I have been unable to resolve this issue for a JSONObject string. this.updateUser({"nam ...

Prevent modal from closing when clicking outside in React

I am currently working with a modal component in react-bootstrap. Below is the code I used for importing the necessary modules. import React from "react"; import Modal from "react-bootstrap/Modal"; import ModalBody from "react-bootstrap/ModalBody"; impor ...

Guide to generating a text string by utilizing the foreach loop

Is there a way to combine text strings from interfaces into a single file for display in UI? The current code is generating separate files for each interface. How can I achieve the expected result of having all interfaces in one file? Additionally, is it ...

What prevents TypeScript from automatically inferring tuple return types in RxJs streams?

When composing an observable stream, the map function infer is a union instead of a tuple. For instance: import { Component } from '@angular/core'; import { from } from 'rxjs'; import { map, tap } from 'rxjs/operators'; expo ...

Encountering the issue of receiving an undefined value when attempting to define a {string} parameter within the "when" section of the step

As a novice in the world of protractor with cucumber, I am faced with the challenge of automating a process where inputting a first name, last name, and postcode creates a new user. In order to achieve this, I have attempted to define the data entry within ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

Managing server errors when utilizing Observables

i am currently developing an Angular 2 application and part of it includes a login feature that utilizes this service. import { Http, Response } from '@angular/http'; import {Injectable} from '@angular/core'; import 'rxjs/add/op ...

Showing data entries in a Gridview when a specific radio button is chosen

I'm working on developing a web portal using the ASP.NET framework in C# with a MySQL database server. On one page, I have 4 radio buttons (SAP Info, DB Info, OS Info, and License Info) along with a grid view. My challenge is figuring out how to disp ...

Invoking a controller from another controller in the Express framework using Typescript

Currently, I am trying to call a controller from another controller in my code. While attempting to pass parameters using {params: {task_id: String(task_id), result}}, TypeScript is flagging an error indicating that res does not have all the required attri ...

Troubleshooting: Vee-validate useResetForm not functioning properly during submission in Vue 3 with Typescript

I've been struggling to reset form data after submission, and it seems like the useResetForm hook isn't working as expected. Code Section <script setup lang="ts"> import CircularProgress from "@/components/CircularProgress. ...

Angular Multiplexed Templates - Utilizing a Variety of Components

I'm looking to create a Multiple Template scenario, but I could really use some guidance. In this scenario, the User has the ability to change the entire template, meaning they can switch between Template 1, Template 2, Template 3, and so forth. Each ...

Why is it that I am limited to running globally installed packages only?

Recently, I made the switch to Mac iOS and encountered an issue while setting up a new TypeScript backend project. All npm packages seem to be not functioning properly in my scripts. Cannot find module 'typescript/bin/tsc' Require stack: - /Users ...

I am looking to append a new value to an array within the state in React

development environment ・ react ・ typescript In this setup, state groups are stored as arrays. If you want to add a group to the array of groups when the onClickGroups function is called, how should you go about implementing it? interface ISearc ...

Is it possible to invoke an AngularJs service by clicking a button?

Recently, I've been working on some AngularJS code involving a service and controller. angular.module('myModule', []).service("AttendanceService", function ($http) { this.getdata = function () { return $http({ ...

Enhance your React application by using a personalized hook that allows you to trigger a function

After creating a custom hook to handle uploads to an AWS S3 bucket, I encountered a small issue. Rather than having the hook execute the logic directly, I decided to create an executable function to return instead. However, I am facing a problem where the ...

Utilizing eight threads in Selenium C# for multi-threaded automation scripts seemed like a smart idea at first. However, after some time, the CPU usage spiked to 100% because the

Selenium Automation Issue in C# Recently, I encountered a problem while running multiple multi-threaded Automation scripts (total of 200 scripts with 8 threads) using Selenium in C#. As the tests were running, the CPU utilization spiked to 100% due to the ...

Displaying Modal from a separate component

CardComponent: export class Card extends Component<Prop, State> { state = { isCancelModalOpen: false, }; marketService = new MarketService(); deleteMarket = () => { this.marketService .deleteMar( ...

Error number 13 encountered during Angular CLI installation process

When attempting to install npm install -g @angular/cli, I encountered the following error: npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules npm ERR! path /usr/local/lib/node_modules npm ERR! code EACCES npm ERR! errno -13 npm ...

typescriptIs it possible to disregard the static variable and ensure that it is correctly enforced

I have the following code snippet: export class X { static foo: { bar: number; }; } const bar = X.foo.bar Unfortunately, it appears that TypeScript doesn't properly detect if X.foo could potentially be undefined. Interestingly, TypeScript ...