Modify associated dropdown menus

I am trying to create an edit form that includes dependent select fields (such as country, state, city). The issue I am facing is that the edit only works when I reselect the first option (car brand) because I am using the event (change) with $event. How can I set a default selected value in the second select field (car model) without having to click on the first select for the event to populate the second select?

Here is my code:

<form #editcarPost="ngForm" (ngSubmit)="updateCar()" [formGroup]="editcarForm">
  <div class="form-group">
    <label for="carbrand_name">Car Brand</label>
    <select class="form-control" id="carbrand_name" formControlName="id_carbrand" (change)="getCarmodel($event)">
   <option *ngFor='let carbrand of carbrands' [value]="carbrand.id_carbrand" >{{carbrand.carbrand_name}}</option>
    </select>
  </div>
  <div class="form-group">
    <label for="carmodel_name">Car Model</label>
    <select class="form-control" id="carmodel_name" formControlName="id_carmodel">
   <option *ngFor='let obj of carmodelArr' [value]="obj.id_carmodel">{{obj.carmodel_name}}</option>
    </select>
  </div>

In my editcar.component.ts file, I have the following setup:

 ngOnInit() {
    console.log(this.router.snapshot.params.id);
    this.dataService.getCars().subscribe(data => this.cars = data);
    this.dataService.getCarbrands().subscribe(data => this.carbrands = data);
    this.dataService.getEditCar(this.router.snapshot.params.id).subscribe((result)=>{
    this.editcarForm = new FormGroup({
      id_carbrand: new FormControl(result[0].id_carbrand, Validators.required),
      id_carmodel: new FormControl(result[0].id_carmodel, Validators.required),
      production_year: new FormControl(result[0].production_year),
      plate_number: new FormControl(result[0].plate_number),
      vin: new FormControl(result[0].vin),
      colour: new FormControl(result[0].colour),
      description: new FormControl(result[0].description),
    })
  
  })
  }

  getCarmodel(event)
  {
    var obj = {
      id_carbrand: event.target.value,
    }
    this.dataService.getCarbrandByID(obj).subscribe(res=>{
        this.carmodelArr = res;
    })
  }

If anyone knows how to set a default value for event.target.value or any other method without needing to click on the first select field, please share your insights!

Answer №1

After some troubleshooting, the issue was fixed by implementing a secondary function called getCarmodelstart with an ID parameter instead of relying on events. Additionally, in the OnInit method, I included the line "this.getCarmodelstart(result[0].id_carbrand);" to properly initialize the process.

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

Why does my test in Angular 2 e2e protactor fail when I do not include browser.sleep()?

While working on my e2e tests, I encountered an issue with a custom select dropdown component I created. When trying to select items in the dropdown, I found that I had to use browser.sleep(...) in my test for it to pass. If I don't include this sleep ...

Suggestions for the output of an Angular 2 async validator when employing observables

How should the customerNameValidator handle the async validation result for the 'customerName' FormControl invalidation? this.customerForm = this.formBuilder.group({ customerName: [this.newCustomerName, [Validators.minLength(2), Validators.requ ...

Using PHP header function to redirect to a specific form on an HTML page: A step-by-step guide

I have a dilemma in my web project. In the index.php file, there are two forms that utilize transitions to switch between pages (Login and Register). When attempting to register a new user in the backend, I check if the user already exists. If they do exis ...

Having trouble retrieving data in Angular from the TypeScript file

demo.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) ...

Comparing two inherited classes in Typescript: A step-by-step guide

Let's say we have two classes: Animal and Dog. The Dog class is a subclass of the Animal class. I am trying to determine the types of these objects. How can I accomplish this task? class Animal {} class Dog extends Animal {} //The object can be of ...

Ways to resolve Cross-Origin Resource Sharing (CORS) issue encountered in Report

I am currently working on an Angular project and trying to render SSRS reports within the app by utilizing a specific package. The application is hosted at http://localhost:52698/ while the SSRS server resides on a different domain http:\ssrsserv ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

Ways to help a child notice when a parent's variable changes

Looking for help with passing data to a child component? Check out this Plunker: http://plnkr.co/edit/G1EgZ6kQh9rMk3MMtRwA?p=preview @Component({ selector: 'my-app', template: ` <input #x /> <br /> <child [value] ...

Deriving data types based on a variable in TypeScript

If I have a dictionary that links component names to their corresponding components like this: const FC1 = ({prop}: {prop: number}) => <>{prop}</>; const FC2 = ({prop}: {prop: string}) => <>{prop}</>; const mapComponents = [ ...

"Perform an upsert operation with TypeORM to create a new entry if it

Is there a built-in feature in TypeORM to handle this scenario efficiently? let contraption = await thingRepository.findOne({ name : "Contraption" }); if(!contraption) // Create if not exist { let newThing = new Thing(); newThing.name = "Contrapt ...

How can I set an array as a property of an object using the Angular Subscribe method?

I'm attempting to retrieve array values from the en.json translation file in Angular and then bind them to an object property using the code snippet below. Here is the TypeScript code: ngOnInit() { this.en = { dayNamesMin: this.translateS ...

An error occurred when attempting to access data within a variable that is undefined, resulting in a TypeError at the errorHandler function

Every time I attempt to send a post, patch, or put request, I keep getting this error. However, there are no issues with get requests. TypeError: Cannot read properties of undefined (reading 'data') at errorHandler (/home/joe/Documents/mypro ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

An automatic conversion cannot handle spaces and prohibited characters in Object keys

The AlphaVantage API uses spaces and periods in the keys. Their API documentation is not formal, but you can find it in their demo URL. In my Typescript application, I have created data structures for this purpose (feel free to use them once we solve the ...

The additional values inserted into the form using jQuery are not being recognized or passed to AngularJS

My form has multiple input fields, some of which are pre-populated when the markup is generated. For example, value=#{ session[:lat] } or simply value='111'. While this appears correct when inspecting the page, Angular does not submit this value. ...

Guide on invoking a private function in Angular2 using RxJS Observables

Greetings, I am a beginner to RxJs and just started learning it today. As a newbie, I have a question regarding its usage. My current task involves extracting XML RSS feed and then converting it into a JSON format. To achieve this, I created a FeedService ...

The function fromEvent is throwing an error stating that the property does not exist on the type 'Event'

I'm attempting to adjust the position of an element based on the cursor's location. Here is the code I am currently using: this.ngZone.runOutsideAngular(() => { fromEvent(window, 'mousemove').pipe( filter(() => this.hove ...

The type argument '(id: any, title: any, body: any, image: any) => Element' does not match the parameter type

Hello there, I am a beginner in React-Native and I'm facing an issue while trying to map data into View. Despite going through the documentation and other resources, I haven't been able to figure out what mistake I might be making. Can anyone hel ...

Choose between using Angular with either PHP and Python or with Django and Python in PHP

For my graduation project, I have developed the frontend using Angular and created a machine learning system with Python. Now, I need to integrate these two components by writing a Web API for Angular using Django, even though I have no prior experience wi ...

Angular asynchronous operations are failing to complete within the specified time frame

Observations suggest that Angular's async from @angular/core/testing is not properly resolving timeouts in tests when a beforeEach contains async as well. Sadly, the bug cannot be replicated on Plunkr or JSFiddle platforms. To reproduce this issue ea ...