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

Numerous sentries summoning an asynchronous function

In my scenario, I have two guards - Guard1 and Guard2. Guard1 is responsible for returning an Observable whereas Guard2 returns a Boolean value. For canActivate: [Guard1, Guard2] If Guard2 were to return false, would the request made by Guard1 be automat ...

Angular: Oops! Encountered some template parsing issues: Surprising closing tag encountered

Recently, I created a brand new project with Angular CLI on 05/25/17. I decided to copy and paste some HTML code into a new component in the project. Surprisingly, this HTML code, which worked perfectly fine as its own standalone page, is now causing compi ...

Tips for avoiding recursive error function calls in Angular 5

Is there a way to avoid repetitive function calls within a recursive function? Take a look at the following code snippet: loadFinalData(id, color){ this.data = this._test.getUrl(id, "white"); this.dataHover = this._test.getUrl(id, "blue"); } pri ...

Incorporate Angular frontend into current website or project

I've successfully built a website using bootstrap, but now I'm looking to integrate Angular in order to transform it into a single page application. The goal is that when a user clicks on a link, only the necessary content will be loaded from the ...

Tips for implementing pagination on a large JSON file without traditional pagination controls

Looking for the best way to implement pagination in a NextJs app that loads products from a local JSON file? This JSON file doesn't have any page properties, so the only option is to limit the number of products shown by using slice: {Object ...

Suggestions for managing the window authentication popup in Protractor when working with Cucumber and TypeScript?

I'm a beginner with Protractor and I'm working on a script that needs to handle a window authentication pop-up when clicking on an element. I need to pass my user id and password to access the web page. Can someone guide me on how to handle this ...

When the first argument is missing, using a recursive constraint default can result in the incorrect inference of the second argument, especially when both arguments share the same generic

Currently, I am developing a TypeScript implementation of a recursive binary search tree (BST) data structure using generic constraints. In order to establish a default for the recursive generic variable T without directly using it in the default declarati ...

Utilizing Angular's NgFor directive to showcase the elements within the array

Just diving into Angular and attempting to access the values within postdata. However, I'm running into an issue where only the first value is being retrieved when I try to iterate over it. Here's a snippet of my code: posts; constructor(priva ...

Even when it appears to be chaotic, the TypeScript array of numbers always manages to find its way back to being sorted

I recently developed a function that aims to verify if an array of numbers is sorted: const checkIfSorted = (numbers: number[]) => { return numbers === numbers.sort((a, b) => a - b); }; checkIfSorted([4, 2, 8, 7, 3, 10, 1, 5, 9, 6]); // This cur ...

Is it possible to verify email input without including standard domains?

Looking to implement validation that excludes common email domains like gmail.com or outlook.com in my project. Here is the current code I have, how can this type of validation be implemented? onboarding.component.html <div class="w-full my-3 md:i ...

Exploring nested promises in TypeScript and Angular 2

I have a method called fallbackToLocalDBfileOrLocalStorageDB, which returns a promise and calls another method named getDBfileXHR, also returning a promise. In the code snippet provided, I am unsure whether I need to use 'resolve()' explicitly o ...

Creating a union type from an array that is not a literal (using `Object.keys` and `Array.map`)

Can a union be derived from a non-literal array? I attempted the following: const tokens = { "--prefix-apple": "apple", "--prefix-orange": "orange" }; const tokenNames = Object.keys(tokens).map(token => toke ...

Modifying one input can impact other input elements without any form of direct connection between them

Below is the HTML code snippet: <tr *ngFor="let row of formData; let i = index" [attr.data-index]="i"> <td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j"> <input type="checkbox" name="row-{{i}}-{{j}}" [ ...

Angular - CSS Grid - Positioning columns based on their index values

My goal is to create a CSS grid with 4 columns and infinite rows. Specifically, I want the text-align property on the first column to be 'start', the middle two columns to be 'center', and the last column to be 'end'. The cont ...

Create an interactive slider using only images in an Ionic Angular content display

I need help transforming the images from WordPress into a slider instead of showing them individually. How can I achieve this? <ion-content padding> <div *ngIf="selectedItem" class="selection"> <h2 [innerHTML]="selectedItem.title.rend ...

Exploring ways to use TypeScript to export a Mongoose model?

There's a module I need to export in order to avoid the error "OverwriteModelError: Cannot overwrite Task model once compiled". I've tried various solutions but none seem to work. The problem lies in the last line (export default models...) impo ...

Tips on utilizing a function that was generated within the constructor

I'm currently in the process of developing a function within the constructor, and it is essential that this function be placed inside the constructor. I am interested in implementing a button to trigger this function from an external source, but unfor ...

The Angular Material Autocomplete component fails to show items upon upgrading the angular/material package to the newest version

Issue with Angular Material Autocomplete component not displaying items after updating angular/material package to the latest version. The autocomplete was functioning correctly with "@angular/material": "^2.0.0-beta.10" but encountered issues when update ...

Utilizing Angular to render JSON data on the screen

Currently, I have my data saved in a database and am retrieving it in Angular. The problem arises when I attempt to display the data as I encounter an error. All I want is to exhibit the question in HTML using ngFor. Being new to Angular, any advice or gui ...

How to disable time selection in owl-date-time picker for Angular 6 inputs

To install the ng-pick-datetime package, use the following command: npm install ng-pick-datetime --save I recently incorporated the Owl Date Time Picker into my project. You can find more information about it here. <input [owlDateTimeTrigger]="dt10" [ ...