Assign a predetermined value to a dropdown list within a FormGroup

I have received 2 sets of data from my API:

{
  "content": [{
      "id": 1,
      "roleName": "admin",
    },
    {
      "id": 2,
      "roleName": "user",

    },
    {
      "id": 3,
      "roleName": "other",

    }
  ],
  "last": true,
  "totalElements": 3,
  "totalPages": 1,
  "size": 20,
  "number": 0,
  "first": true,
  "sort": null,
  "numberOfElements": 3
}

and also user information:

{
  "id": 1,
  "userName": "admin"
  userRole[
    "id": 1,
    "roleName": "admin",
  ]
}

In my HTML, I am trying to display the list of roles:

<div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">{{ls.roleName}}</option>
  </select>
</div>

However, the UI is showing: [admin],[admin],[user],[other]

I attempted to eliminate duplicate roles using *ngIf:

<div class="form-group">
  <label>Roles</label>
  <select formControlName="roles" class="form-control" id="roles">
    <option>{{user.userRole.roleName}}</option>
    <option *ngFor="let ls of roles">
      <div *ngIf="user.userRole.roleName!=ls.roleName">{{ls.roleName}}</div>
    </option>
  </select>
</div>

Unfortunately, the UI now displays:[admin],[blank],[user],[other]

I would appreciate any advice on how to correctly display the list of roles.

Answer №1

I have discovered the answer for user [attr.selected]:

<select formControlName="roles" class="form-control" id="roles"  >
<option *ngFor="let rl of roles;" 
[attr.value]='rl.id' 
[attr.selected]="rl.id == desc ? true : null">
{{rl.roleName}}
</option>
</select>

Answer №2

<div class="form-item">
  <label>User Roles</label>
  <select formControlName="userRoles" class="role-select" id="userRoles">
    <option *ngFor="let role of userRolesList" [selected]="role.id === currentUserRole.id">
      {{role.roleName}}
    </option>
  </select>
</div>

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

To enhance user experience, it is recommended to reload the page once

Hello, I'm looking for a way to automatically refresh the page after submitting an AJAX form. Currently, I have an onClick function that seems to refresh the page, but I still need to press F5 to see the changes I've made. Here's the JavaSc ...

Tips for improving the loading speed of a table during scrolling with JavaScript

Is there a way to speed up the loading time of a <table> with 20000 rows? As I scroll through the page, it feels very sluggish and takes around 4-5 seconds to load the remaining table data. I'm unsure how to tackle this issue, which is why I h ...

Learn how to easily copy the success result from an Ajax call to your clipboard

Is there a way to use an ajax method to retrieve data from a controller and display it in a JQuery Dialog Box? I want to add a button within the dialog box that allows the user to easily copy the data with a single click, instead of having to manually high ...

React fails to display the content

Starting my React journey with Webpack configuration. Followed all steps meticulously. No error messages in console or browser, but the desired h1 element is not showing up. Aware that React version is 18, yet working with version 17. App.jsx import Reac ...

Changing the icon on click in react: a step-by-step guide

I have two MUI icons that I need to toggle with every click. I created a component for them, and one of the props (called btnClicked) controls the state. However, when clicking on the component, the icon buttons do not change. Here is the code: import Reac ...

use ajax to post saved data to a WebAPI in php

I have successfully implemented the code to save data in a custom table using Ajax. Now, I need to figure out how to send this data to an asp.Net API using js/jQuery. How can I achieve this? Below is my HTML form and JS code: <div id="inline1" class= ...

Set the cookie to expire in 5 minutes using PHP, JavaScript, or jQuery

Is there a way to set a cookie in PHP that expires in 5 minutes? I am comfortable with the setcookie() function, but unsure about how to set the expiration time. Any explanation would be greatly appreciated. Could someone please guide me on how to achieve ...

What is the best way to attach an onClick event to a PHP-generated link?

Currently, I'm attempting to implement an onclick event on a link within a PHP file. $body2 .= '<td class="sampling-list-td download-link">' . '<a ' . 'class="sampling-list-download" ' . 'href="#" ' . ...

Unable to Transmit Authorization Header in Cross-Domain Access Situation

My Node.js server has cross-origin communication enabled, allowing my Vue application to access its API from a different origin where static assets are served. This is achieved by setting the following code in Node.js: res.setHeader('Access-Control-Al ...

Executing a Javascript function within a PHP script

I am trying to retrieve JSON data from a JavaScript function and use it as a variable in PHP. Here is the function I have: <script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script> <script> $(fu ...

Is there a way to incorporate the "Handoff to Human" feature in a Microsoft Teams bot app by utilizing the Teams Toolkit? Can this functionality be implemented using TypeScript?

Can someone assist me with figuring out how to incorporate the "handoff conversation to human agent mechanism" in my project using TypeScript, Microsoft Bot Framework, and Teams Toolkit? ...

Tips for storing an unmatched result in an array with a Regexp

Is it possible to extract the unmatched results from a Regexp and store them in an array (essentially reversing the match)? The following code partially addresses this issue using the replace method: str = 'Lorem ipsum dolor is amet <a id="2" css ...

Can the jQuery live function be triggered without the need for an event?

Using the live function in jQuery requires an event to trigger it. More information can be found in the official API documentation. $(".xyz").live('event', function(){ }); I am trying to make the above function run as soon as the dynamicall ...

Creating an AJAX data form in a JSP scenario

I want to correctly set up the data parameter for the ajax call. <script type="text/javascript"> $(document).ready(function() { $('#call').click(function () { $.ajax({ type: "post", ...

Utilizing Ajax for dynamic PHP result determination

HTML CODE <div class="card text-center pricing-card mb-20"> <ul class="list-group list-group-flush"> <?php $gbewas = mysqli_query($con,"SELECT * FROM price"); while($okks = mysqli_fetch_array($gbewas)) { ?> <li cla ...

Calculating a Price Quote

I have created a dynamic quote calculator for a Next.js project that allows users to calculate prices based on word count and selected languages. Currently, the price is calculated using a fixed rate of 0.05 per word. 'use client'; import { useS ...

Display alternative text dynamically

Trying to gain a deeper understanding of state in react, this is a perfect example to me. When I say dynamic, I mean displaying the output below instantly as it is entered in the form. class Demo extends Component { constructor(props) { super ...

Trigger a function when the browser automatically populates an input field

I am attempting to trigger a function that can detect if the browser has autofilled a field and then add a specific class to it. After finding a thread with a solution that mostly works, mentioned here: Here is how I implemented it: $.fn.allchange = fun ...

Reload the Node.js webpage

Is there a method to automatically refresh a Node.js page following a socket.io event? var messageDynamic = "Initial status"; app.get("/", function(request, response) { response.setHeader('Content-Type', 'text/plain'); respons ...

Use the button to trigger the opening of the datepicker in React material UI

Currently, I am incorporating a Datepicker in my project using React Material UI. <TextField id="datetime-local" label="Next appointment" type="datetime-local" defaultValue="2017-05-24T ...