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

Is there a way to make PrismaClient return DateTime fields as Unix timestamps rather than JavaScript date objects?

When utilizing the PrismaClient for database interaction, DateTime fields are returned as JavaScript Date objects instead of Unix timestamp numbers. Despite being stored as Unix timestamp numbers in the database itself, I require the dates to be retrieved ...

What is the best way to implement CSS Float in typescript programming?

For a specific purpose, I am passing CSS Float as props. To achieve this, I have to define it in the following way: type Props = { float: ???? } const Component = ({ float }: Props) => {......} What is the most effective approach to accomplish this? ...

Typescript fill() function like Laravel's fill()

One interesting feature in Laravel is the fill() method of every database model, which only assigns fields marked as "mass assignable" to the class property. (https://laravel.com/docs/5.8/eloquent#mass-assignment) public class Rectangle { protected $f ...

What is the benefit of utilizing ngSubmit over just using a basic button and function?

Lately, I've been pondering whether to utilize ngSubmit or simply bind a (click)="submit()" on a button. There's been much debate about using submit and ngSubmit, but is it necessary to rely on the traditional HTML submit method? Particularly wh ...

Error deploying to Heroku: Unable to obtain access

I've been working on deploying my MEAN application to Heroku, and while the deployment is successful, I'm encountering an error when trying to open the application - it keeps showing a "CANNOT / GET" message. Upon checking the console, I see the ...

Encountering the error message "PHPUnit_Extensions_Selenium2TestCase_WebDriverException: sendKeysToActiveElement" while trying to input data into a form using Selenium2 and PHP

I'm currently working on a Selenium2 test case driven by PHPUnit where my main goal is to fill out a form. Successful Scenario - Green Bar: This is the setup: protected function setUp() { $this->setBrowser( 'firefox' ); $this-& ...

The argument provided, 'Item', cannot be assigned to the parameter, 'string'. TS2345 error encountered

Encountering an issue with type 'string'. Error code TS2345 Problem: Argument of type 'Item' is not compatible with parameter of type 'string'. TS2345 filter(resortList:ResortResult[], selectedFilters:SelectedFilters) { ...

Tips for verifying the response and status code in Angular 8 while uploading a file to an S3 Presigned URL and receiving a statusCode of 200

Looking to Upload a File: // Using the pre-signed URL to upload the file const httpOptions = { headers: new HttpHeaders({ 'Content-Disposition': 'attachment;filename=' + file.name + '', observe: 'response' }) }; ...

Customize Angular Material's Mat-Dialog background blur/darkening effect

Greetings, dear community members, I am currently utilizing angular along with angular material in my projects. By default, when a material dialog is opened, it slightly darkens the background. However, I am interested in having a blurred background inst ...

Alternative for using useRouteMatch to retrieve parameters

I'm currently refactoring this code and struggling to find a suitable replacement for this section. This is due to the react-router-dom v6 no longer having the useRouteMatch feature, which I relied on to extract parameters from the URL: import React, ...

Unlock the canGoBack feature in your Ionic 5 app with these simple steps!

I'm currently working on implementing a back button in my Ionic app, but I am running into an issue. I need to hide the back button when it's at the root level, which is dynamic and can change based on the flow of the app. I came across some code ...

Show blank value if there are no search results, along with an additional menu option

I am currently working on a Typeahead feature with a customized menu using the renderMenu method. In this setup, I have added 2 custom menu items at the bottom - one divider and a button. An issue arises when there are no search results. If I do not inclu ...

Setting up Angular on your Mac

Recently, I attempted to set up Angular on my macOS system. After confirming that I have npm 5.6.0 and node 8.11.1 installed, I proceeded with sudo npm install -g @angular/cli. It appeared to be successful at first, but upon running ng --version, the follo ...

How do I loop through each object within an observable that contains an array of objects in Angular 2?

Hey everyone! I'm currently in the process of upgrading my skills to Angular 2 and I have a few questions. One of them being, how can I iterate through each object in an observable array object? I was able to successfully retrieve data from "api/v1/e ...

Encountering issues when passing a string as query parameters

How can I successfully pass a string value along with navigation from one component to another using query parameters? Component1: stringData = "Hello"; this.router.navigate(['component2'], { queryParams: stringData }); Component2: ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

Incorporating Vaadin components into an Angular2-seed project

Hi there, I've been encountering an issue while trying to integrate Vaadin elements into my Angular2 seed project. The Vaadin team has recommended that I upgrade the systemjs.config.js file by specifying the path names for Vaadin elements like this: ...

After updating from angular4 to angular 5, the npm test is failing with the error message "TypeScript compilation cannot find test.ts file"

After upgrading my app from Angular4 to Angular 5 using the steps provided on https://update.angular.io/, I encountered an issue. While I can successfully run ng-serve and ng build without any problems, the npm test command for ng test is failing with the ...

Utilize TypeScript to access scope within a directive

Is there a way to access the controller's scope properties using my custom TypeScript directive? For example, in this snippet below, I am trying to retrieve and log scope.message: /// <reference path="typings/angularjs/angular.d.ts" ...

Issue with Angular 2 directive update detection; unresolved directive not refreshing

I have created an Angular 2 application that displays a number which can be either negative or positive. In order to change the font color to red when the value is negative, I've implemented a directive. This number gets updated constantly through an ...