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

Having trouble installing the 'ws' npm package on MacOS Big Sur?

Every time I try to install the websocket package using "npm install ws", I keep getting this error message: npm ERR! code ENOSELF npm ERR! Refusing to install package with name "ws" under a package npm ERR! also called "ws". Did you name your project the ...

In Vue, props are not automatically assigned; be sure to avoid directly mutating a prop when assigning it manually to prevent errors

I am working with two Vue components: GetAnimal.vue and DisplayAnimal.vue. GetAnimal.vue sends a JSON object containing animal data to DisplayAnimal.vue using router push. DisplayAnimal.vue then displays this data. The process flow is as follows: I navigat ...

Why aren't the validations being set when creating Angular forms using formControl.values?

I had to structure the form in a specific way in my app.ts file -> courseNameControl = new FormControl("", [Validators.required,Validators.minLength(2)]); contentControl = new FormControl("", Validators.required); form = { cours ...

Testing Angular directives using $window and $event in unit tests

My directive is simple - it overrides click behavior to trigger a full page reload. However, I am struggling to write a Unit Test for this directive. It seems like the injection of $window is not working properly, resulting in an error when running the tes ...

Having difficulty constructing a full stack application using Express

I've been struggling to configure a full stack app using create-react-app with Express and TypeScript. My main issue is figuring out how to compile the server files into a build folder. I have separate tsconfig files for the server and create-react-ap ...

Having trouble with playing the appended HTML5 Video?

Having trouble getting a video player to display after clicking a button. This is the code I use to add the video player in index.html: $("#videoContainer").append( "<video id=\"video-player\" width=\"100%\" height ...

Preventing typing during onKeyDown event in React/JavaScript and other languages

One of the reasons why I opt to use onKeyDown is because the language for typing is Korean. With multiple inputs on the page, my aim is to prevent users from typing more than 20 bytes. //this function calculates the byte length const getByteLength = (s,b ...

Exploring route grouping with angular ui-router

Is it possible to group routes in ui-router? Consider the following routes in my app: #/products/p1 #/products/p2 #/products/p3 One way to define states is as follows: .state('products.p1') .state('products.p2') .state('product ...

SVG tags are not functioning properly

Hello, I am new to working with SVG files. I have a set of icons created using SVG and I am attempting to use the <use> tag in order to display a specific part of an SVG file. However, I seem to be encountering some issues and I am unable to identi ...

Converting API response into a class instance using `class-transformer` in TypeScript: A step-by-step guide

When working with TypeScript, I have a regular method called Request(method: HttpMethod, url: string, ...) that is used for calling APIs. Now, my goal is to convert the response from this API request into an instance of a class using class-transformer (or ...

Data cannot be cleared in the service

I have set up a customer shopping cart on the client side of my application, with a controller managing the functions of the cart and a service injected into that controller. Upon loading the page, I retrieve the contents of the cart from localStorage and ...

Element sticking and bouncing

I'm currently facing an issue with Sticky-kit where one of my elements jumps when it reaches the bottom of its parent div. Below is the code snippet: <div class="wrapper"> <div id="bg"> <div id="text"> Lorem ipsum dolor sit a ...

Error in TypeScript when using Vue/Nuxt.js: The property 'latitude' is not found in the type '(() => any) | ComputedOptions<any>'

As a newcomer to Vue.js, I am currently utilizing it with Typescript on a Nuxt.js (v2.15.8) application. The code snippet provided below is functioning correctly: export default Vue.extend({ name: 'MyComponent', ...

The attempt to update several partial views using Jquery, MVC, and Json is currently malfunctioning

I am facing issues with updating multiple partial views using jQuery, MVC, and JSON. The partial views on my page are not getting updated. Below is the code for my view: Here is the code for my controller: public class GetStudentsController : Controlle ...

Having trouble converting binary data to base64 using GridFS-stream

As I attempt to convert some binary data from uploaded images to base64 in order to display an image, the terminal is throwing back this error: TypeError: Cannot read property 'on' of undefined I find it puzzling, as when I post I also utilize ...

When Ajax attempts to run a PHP page, it redirects me to a different page

My goal is to create a live chat feature using PHP, MySQL, and AJAX. I have almost got it working perfectly, but I'm stuck on how to submit the chat message without refreshing the page. I have a PHP page called sendchat.php that takes input data and s ...

How can a command in a test be executed that is located within a specific "section" in Nightwatch?

I've been utilizing nightwatch for my test automation. Within my page object, I have a "section" containing various commands. However, when attempting to call these commands in the test script, I encountered an error stating "section is not a function ...

Problem: Implementing a horizontal scrolling feature using Skrollr

I'm interested in creating a horizontal animation controlled by skrollr. As I scroll down, I want the elements on my page to move from left to right within my container. When all elements have the same width, setting the scrolling data from 100% to 0 ...

Determining the exact number of immediate descendants within a ul element, while disregarding any script elements

Here is the HTML structure I am working with, which contains a script tag: <ul id="list"> <li class="item1"><a href="#">Item 1</a></li> <li class="item2"><a href="#">Item 2</a></li> <li ...

"Enhancing Form Validation with ng-remote-validate Directive and Multiple Parameters

Exploring the use of ng-remote-validate directive for remote validation has piqued my interest. I am currently wondering how to send multiple values in the request to the server. The current implementation is functioning as intended with the following: &l ...