Updating ComboBox Selection in Angular 4

When attempting to populate a combobox with the value from a selected row, only the inputs are loading.

This section is part of my page:

`    <form class="form-horizontal form-label-left parsleyjs" method="post" data-parsley-priority-enabled="false" novalidate="novalidate">
      <fieldset>   
        <div class="form-group row">
          <label class="form-control-label labelName" for="basic-change">
           Name
          </label>
          <div class="inputName">
            <input #newRole type="text" id="basic-change" name="basic-change" class="form-control" data-parsley-minlength="4" data-parsley-trigger="change"
              maxlength="50" value="{{role.name}}" required="required">
          </div>
        </div> 
         <div class="inputName">
            <select #newEnv class="form-control" required="required">
                    <option value="b">Back Office</option>
                    <option value="c">Casino</option>
                    <option value="s">Store</option>
                </select>
          </div>
          div class="form-group row">
          <label class="form-control-label labelName" for="basic-change">
           Description
          </label>
          <div class="inputName">
            <input #newDesc type="text" id="basic-change" name="basic-change" class="form-control" data-parsley-minlength="4" data-parsley-trigger="change"
              value="{{role.description}}" required="required">
          </div>
          </fieldset>
         </form>

Below is my component:

export class RolesReplaceComponent implements OnInit {
@ViewChild('modal') public modal: ModalDirective;
mensaje: string;
error: boolean;
role;
private isLoading = false;
constructor(
private route: ActivatedRoute,
private router: Router,
private svrRole: RoleService,
private http: Http,
private trans: TranslateService, ) {
this.error = false;
 }

ngOnInit(): void {
jQuery('.parsleyjs').parsley();
this.isLoading = true;
this.svrRole = new RoleService(this.http);
this.route.params
  .subscribe(
  param => {
    this.svrRole.getById(param['id'], null)
      .subscribe(
      resp => {
        console.log(resp);
        this.role = resp.data.data;
        console.log(this.role);
        this.isLoading = false;
        console.log('Que sucedio?');
      },
      error => console.log("Error on edit-roles-services ", error));
    }
   );
 }
}

While the same approach works for loading the inputs, it fails for the <select>.

Any suggestions on how to make it work?

Answer №1

After a quick and simple 2-line addition, I was able to get it working smoothly. I just had to define the variable 'options' in the component like this:

options:any = [{value:'b', name:"Back Office"},{value:'c', name:"Casino"},{value:'s', name:"Store"}];

Then, I replaced the existing options with the new ones using the following code:

<option *ngFor="let p of options" [value]="p.value" [selected]="p.value == role.environment">{{p.name}}</option>

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

Troubleshooting Standalone Component Routing Issues in Angular 16

For my Angular 16 project code, visit this link To create the Angular 16 project with routing enabled, I used the following command: ng new myapp --standalone Then, I added other components using: ng g c components/home The boilerplate files are differe ...

Nest faces difficulty resolving the dependencies required by the TMPController

I've tried everything to fix this error, but nothing seems to be working. tmp.module.ts import { Module } from "@nestjs/common"; import { TMPController } from "./tmp.controller"; import { TMPService } from "./tmp.service"; @Module({ controllers: ...

What is the proper way to declare an array of arrays with interdependent types?

Imagine I am creating a directory of tenants in a shopping center, which can be either shops or restaurants. These tenants fall into various categories: type ShopTypes = | `Accessories` | `Books` | `Clothing`; type RestaurantTypes = | `Div ...

tips for replacing multiple route parameters in Angular using the replace function

I am facing an issue when trying to replace multiple parameters using the angular replace function. The problem is that the function only detects the first parameter. For example, if I have this route admin/management/{type}/card/{id}, and use the route.r ...

Failed to import due to an error from the downloaded dependency

I'm encountering an import error in the @react-three module of my downloaded package. ./node_modules/@react-three/drei/node_modules/troika-three-text/dist/troika-three-text.esm.js Attempted import error: 'webgl-sdf-generator' does not cont ...

Identifying Classifications Based on Input Parameters

I'm encountering some difficulty in typing a function that calls an external API and returns data based on the parameters sent. Here is what I have so far... import axios from 'axios'; interface IGetContactArgs { properties?: string[]; } ...

Issue with `import type` causing parse error in TypeScript monorepo

_________ WORKSPACE CONFIGURATION _________ I manage a pnpm workspace structured as follows: workspace/ ├── apps/ ├───── nextjs-app/ ├──────── package.json ├──────── tsconfig.json ├───── ...

Experimenting with HttpClient request using callFake() method

I am currently facing a challenge while trying to devise a spec for testing a method within my Angular service that initiates a GET request. The main issue I'm encountering is how to simulate the method returning an error instead of the expected respo ...

Component in Angular2 encountering a null value

Unexpected situations may arise where "this" becomes null within a component. So far, I have encountered it in two scenarios: 1) When the promise is rejected: if (this.valForm.valid) { this.userService.login(value).then(result => { ...

I am having trouble getting my angular image to switch using angular animations

I am attempting to implement image swapping using Angular animations based on a 10-second timer. However, the swap is not occurring and I have been troubleshooting without success. The goal is for the images to change when the timer reaches 5 seconds, but ...

What is the best way to process a date string and format it in TypeScript?

My task involves receiving a date in string format as 20160229000000 ('YYYYMMDDhhmmss'). I need to take this string and display it in DD-MON-YYYY format using Typescript. Instead of relying on an angular package like DatePipe, I am working with ...

Dealing with Angular State Management Across Components (Direct Dependency): encountering a NullInjectorError - R3InjectorError

I have encountered a NullInjectorError in my Angular application and I am seeking assistance in resolving it. To provide context, my application consists of three main components: ProductRegistrationAndListingScreen, ProductList, and ProductRegistration. ...

What is the best way to handle updating an npm package that is not the desired or correct version?

I've been experimenting with querying data on Firebase using querying lists. My attempt to implement functionality similar to the documentation resulted in this code snippet: getMatchesFiltered(matchId: string, filter: string, sortDirection: string, ...

Achieving a shuffling CSS animation in Angular 8 may require some adjustments compared to Angular 2. Here's how you can make it

Seeking assistance with animating an app-transition-group component in Angular 8. My CSS includes: .flip-list-move { transition: transform 1s; } Despite calling the shuffle function, the animation always happens instantly and fails to animate properly ...

Exploring Angular: distinguishing between sessions on separate tabs

I am currently working on a web application that utilizes Angular for the front end and a Django Rest API for the back-end. In some cases, I need the Django Rest API to be able to distinguish between polling requests using session IDs. After conducting som ...

Angular2 recursive template navigation

Is it possible to create a recursive template in Angular 2 without using ng-include? It's puzzling why this feature seems to be missing in Angular 2... HTML: <div ng-app="app" ng-controller='AppCtrl'> <script type="text/ng-templat ...

"Converting to Typescript resulted in the absence of a default export in the module

I converted the JavaScript code to TypeScript and encountered an issue: The module has no default export I tried importing using curly braces and exporting with module.exports, but neither solution worked. contactController.ts const contacts: String[ ...

Guide to summing the values in an input box with TypeScript

https://i.stack.imgur.com/ezzVQ.png I am trying to calculate the total value of apple, orange, and mango and display it. Below is the code I have attempted: <div class="row col-12 " ngModelGroup="cntMap"> <div class="form-group col-6"> ...

Angular Dialog Component: Passing and Populating an Array with Mat-Dialog

Here's the situation: I will enter a value in the QTY text field. A Mat dialog will appear, showing how many quantities I have entered. My question is, how can I iterate an object or data in the afterclosed function and populate it to the setItem? Cur ...

The 'toDataURL' property is not recognized on the 'HTMLElement' type

Hey there! I'm new to TypeScript and I've been experimenting with generating barcodes in a canvas using JSBarcode and then adding it to JSpdf as an image using the addImage function. However, I keep encountering the error mentioned above. barcod ...