Updating the dropdown option value in Angular 10's edit component

In my Angular and ASP.NET application, I have an edit form in a component with multiple select options in a dropdown list. When displaying all data in the edit form, the dropdown list fields are displayed as empty instead of showing the previously stored values. I need to set the selected option value in the dropdown list when navigating to the edit form in edit.component.html. Here is the code in my edit.component.ts:


  id: number;
  userForm: FormGroup;
  Charity: Charities;
  Charities: Charities[];
  users: Users[];
  Cities: City[];
  Categories: Category[];
  selected: any;
  Regions: Region[];

  constructor(private activateRoute: ActivatedRoute,private route: Router,private fb : FormBuilder, private CharityService : CharityService,private toastr: ToastrService , private RegisterService : AccountService, private router : ActivatedRoute) { }

  ngOnInit(): void {
    var userId = this.router.snapshot.params['id'];
    this.setForm(userId);
    this.CharityService.GetAllCategories().then(res => this.Categories = res as Category[])
    this.CharityService.GetAllRegions().then(res => this.Regions = res as Region[])
    this.CharityService.GetAllUsers().then(res => this.users = res as Users[]); 
    this.users = [];
  }

  get editFormData() { return this.userForm.controls; }

  private setForm(id:number) {
    this.CharityService.GetCharit(id).then(x => {

      this.Charity = x;
      this.userForm = this.fb.group({
        id: [this.Charity.id, [Validators.required]],
        name: [this.Charity.name, [Validators.required]],
        phone: [this.Charity.phone, [Validators.required]],
        SubCategoryId: [this.Charity.SubCategoryId, [Validators.required]],
        RegionId: [this.Charity.RegionId, [Validators.required]],
        CityId: [this.Charity.CityId, [Validators.required]],  
        Category:[this.Charity.Category, [Validators.required]],
      });
    });

  }

This is edit.component.html:

For example, formControlName="SubCategoryId"


<select class="custom-select" [(ngModel)]="Categories" formControlName="SubCategoryId" [ngClass]="{'is-invalid' :!this.userForm.get('SubCategoryId').valid && this.userForm.get('SubCategoryId').touched}" [(value)]="selected" required>
<option selected value="" disabled class="dove">اختر التصنيف</option>
<option *ngFor="let cat of Categories" [value]="cat.id">{{cat.subCategoryName}}</option>
</select>

Can anyone help me?

Answer №1

Consider trying out a solution like this one, as it has worked well for me:

<select class="custom-select mr-sm-2" id="SubCategoryId" #SubCategory formControlName="SubCategoryId">
   <option *ngFor="let cat of Categories; let i = index" [ngValue]="cat.id">
       {{cat.value}}
   </option>             
 </select>

Answer №2

To assign the chosen value for the dropdown menu, you can utilize the following code snippet within the typescript file:

this.userForm.controls.get('SubCategoryId').setValue('' + this.Charity.SubCategoryId + '');

Appreciate it!

Answer №3

If you're encountering an issue where the control values aren't binding because the lookup list hasn't loaded from the server yet, here's how you can verify this by populating your lists with dummy data such as this.Categories = [1,2,3].

The solution is straightforward:

Modify your ngOnInit to be an async function and use await within it for the necessary services before updating the form values.

async ngOnInit(): void {
        const userId = this.router.snapshot.params['id'];
        await Promise.all([
            this.CharityService.GetAllCategories().then(res => this.Categories = res as Category[]),
            this.CharityService.GetAllRegions().then(res => this.Regions = res as Region[]),
            this.CharityService.GetAllUsers().then(res => this.users = res as Users[])
        ]);

        this.setForm(userId);
        this.users = [];
    }

Just a note, I've used Promise.all() for parallel execution only. If needed, you can use await for each service call sequentially. Hopefully, this resolves your problem.

Another suggestion is to initialize your form once and then patch values:

private _initForm(){
    this.userForm = this.fb.group({
        id: ['', [Validators.required]],
        name: ['', [Validators.required]],
        phone: ['', [Validators.required]],
        SubCategoryId: ['', [Validators.required]],
        RegionId: ['', [Validators.required]],
       CityId: ['', [Validators.required]],  
       Category:['', [Validators.required]],
  });

}

Call this in your ngOnInit:

async ngOnInit(): void {
    _initForm();
    //rest of code
}

In your setForm function, exclusively patch the values like so:

this.userForm.patchValue({ id : newValue });

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

Is it possible to integrate ngx-translate with database-supported translations?

I am managing a vast database (pouchDB) that stores translations, with each language having its own dedicated database. How can I leverage ngx-translate to easily access these translations directly from the database? ...

"Refining MongoDB queries with a filter after performing a populate

I want to retrieve all records with populated attributes in a query. Here is the TypeScript code: router.get("/slice", async (req, res) => { if (req.query.first && req.query.rowcount) { const first: number = parseInt(req.qu ...

Guide on entering text into an Angular input field with Selenium in Python after navigating tabs

After switching tabs, I am attempting to enter text into an Angular input field. However, I keep encountering the following errors: AttributeError: 'tuple' object has no attribute 'send_keys' or ElementClickInterceptedException or NoS ...

Tips for accessing touch events within the parent component's area in React Native

I implemented the code below in my React Native app to disable touch functionality on a specific child component. However, I encountered an issue where the touch event was not being detected within the area of the child component. How can I fix this prob ...

Function 'await' fails to execute

Within this function, I am iterating through an array of strings, each representing a user's UID. The goal is to access each user's profile, retrieve the most recent reputation (similar to SO), and then add a map of the UID and reputation to a ne ...

Troubleshooting Issue: Angular 6 - Authentication token interceptor not including headers

After experimenting with various approaches using Angular 6 for the past couple of days, I recently tried implementing a solution mentioned in this post: . Despite my efforts, the header in the requests still remains unset. import {Inject, Injectable} fro ...

Error: No injection provider found for function(){}!

After countless hours of setting up a custom AOT in Angular 7 project without CLI and debugging, I have encountered the following error: Uncaught Error: StaticInjectorError(Platform: core)[function(){}]: NullInjectorError: No provider for function(){}! ...

Leverage session variables for Hangfire recurring tasks

I recently added the hangfire integration into my Asp.net web application and encountered an issue while trying to use session variables within a Hangfire Recurring Job. Here's a snippet of my code: public class Startup { public void Configuratio ...

Is it considered an anti-pattern for certain components within a tile system to share a viewmodel when the parent web component has multiple child components?

Creating an Angular application involves a parent component that contains child components. I am looking for a way to share functionality among the components without resorting to creating services for each one. One approach would be to build services and ...

Complete a submission using an anchor (<a>) tag containing a specified value in ASP.Net MVC by utilizing Html.BeginForm

I am currently using Html.BeginFrom to generate a form tag and submit a request for external login providers. The HttpPost action in Account Controller // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public Acti ...

Unable to find a matching router for the Angular component

In my project, I am tasked with creating a specific path structure: "myapp/category/subcategory". The "myapp/" part is fixed, while the category is represented by the variable "cat.title" and subcategory by "sub.title". To achieve this, I have JSON data ...

List of C# DTO containing two separate lists

Forgive me if this question is rather basic, as I am a newcomer to C#/dotnet. If the solution to my query is obvious, please direct me accordingly. Within my DTO class, I have the following code snippet: public class LessonDetailView : BaseResult { pu ...

angular2-mdl encountered a 404 error and could not be located

I have encountered a strange 404 error stating that the page is not found. Despite installing angular2-mdl using npm install angular2-mdl --save and confirming its presence in the node_modules directory, the error persists. Below is a snippet from my app. ...

Submitting an Angular form in sections or all at once: A guide

Is there a way to submit a form in parts and together? I have a large form with multiple key combinations that need to be sent when editing fields separately. These parts are also utilized in various sections of the application. How can I make the forms in ...

Incorporating the Angular "dist" build file into the Node.js server.js script

Having some trouble deploying my MEAN stack app on Heroku. Managed to commit the app, but struggling to connect the ng build "dist" file to my server.js file. This is the snippet from my server.js file where I'm attempting to link the file: var dist ...

What are the drawbacks of starting with Angular CLI?

Contemplating whether to incorporate Angular CLI into my upcoming project has been on my mind. My main motivation for considering it is to bypass the complexities of setting up a new project and instead focus on mastering the new version of Angular while c ...

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

Having trouble displaying toasts on my website using Angular Material design and $mdToast

Hello there, I am very new to AngularJS, and I have just started using the basic function Show() from $mdToast. Below is the complete code that I have written for this issue, and I would greatly appreciate any help you can provide. 'use strict&apos ...

Does a typescript definition file exist for Apple MapKit JS?

Before embarking on creating one, I'm curious if anyone has come across a typescript definition file (.d.ts) for Apple MapKit JS? ...

What is the process for validating multiple check boxes using the reactive forms module?

I thought this would be a simple task, but I'm having trouble figuring it out. There are three checkboxes and I need to ensure that the user selects only one. The validator should check if any of the other two checkboxes have been selected and preven ...