What is the best way to clear the previous selection in an Angular form once the available values have been updated?

My form displays like this when everything is selected:

https://i.sstatic.net/1kp0w.png

If the user changes the brand, I want it to look like this:

https://i.sstatic.net/hFVy8.png

The options in the second dropdown list are based on the selection in the first dropdown list, and the colored boxes act as radio buttons that change based on the previous selections.

Currently, I can choose a 'Toyota Furious FT18DV blue' without the form validating until all values are checked. However, if I change either of the dropdown list selections, the form doesn't clear the later inputs and still validates even though the combination should not be possible.

How can I deselect the outdated values in the later controls and reset the validation?

@Component({
  selector: 'app-car-chooser',
  templateUrl: './car-chooser.component.html',
  styleUrls: ['./car-chooser.component.css']
})
export class CarChooserComponent {

  cars: Car[];
  brands: string[];
  formBuilder: FormBuilder = new FormBuilder();
  colors: string[];
  carChooserForm: FormGroup;
  car: string[] = undefined;
  brandToModelsPipe: BrandToModelsPipe = new BrandToModelsPipe();
  brandModelToColorsPipe: BrandModelToColorsPipe = new BrandModelToColorsPipe(); // 

  constructor(enumPipe: EnumToArrayPipe) {
    this.generateCars(10);
    this.brands = enumPipe.transform(Brand).map(b => Brand[b]);
    this.colors = enumPipe.transform(Color);

    this.carChooserForm = this.formBuilder.group({
      brand: ['', Validators.required],
      model: ['', Validators.required],
      color: ['', Validators.required]
    });
  }

  onSubmit(customerData): void {
    this.carChooserForm.clearValidators();
    this.carChooserForm.reset();
    console.warn(customerData);
    this.car = customerData;
  }

}
.colorBox {
  all: unset;
  display: inline-block;
  width: 20px;
  height: 20px;
  margin: 5px;
  border: 1px solid rgba(0, 0, 0, .2);
}
<div id="zad5">
  <form [formGroup]="carChooserForm" (ngSubmit)="onSubmit(carChooserForm.value)">
    <label>
      Choose the brand:
      <select formControlName="brand">
        <option *ngFor="let brand of brands" [value]="brand">{{brand}}</option>
      </select>
    </label>
    <br>
    <label>
      Choose the model:
      <select formControlName="model">
        <option *ngFor="let brandModel of carChooserForm.controls['brand'].value | brandToModels : cars"
                [value]="brandModel">
          {{brandModel[1]}}
        </option>
      </select>
    </label>
    <br>
    <label>
      <div>
        Choose the color:
      </div>
      <input *ngFor="let ourcolor of (carChooserForm.controls['model'].value | brandModelToColors : cars)"
             class="colorBox" formControlName="color" name="color" [value]="ourcolor" type="radio"
             [style]="'background-color:' + ourcolor">
    </label>
    <br>
    <button type="submit" [disabled]="!carChooserForm.valid">Submit</button>
  </form>
  <app-car-item *ngIf="car !== undefined" [car]="car">asdsa</app-car-item>
</div>

Answer №1

To monitor changes in field values, you can subscribe to the valueChanges event on the particular field. For instance, if you wish to reset the value of a second control whenever the first one changes, you can implement something like this:

this.userInfoForm = this.formBuilder.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required]
});

const firstNameCtrl = this.userInfoForm.get("firstName");
const lastNameCtrl = this.userInfoForm.get("lastName");
firstNameCtrl.valueChanges.subscribe(val => {
    lastNameCtrl.setValue(null);
});

Take a look at this live demonstration

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

There is a type error in the dynamic assignment in TypeScript. I have various data that need to be fetched from one another

const obj1 = { a: 1, b: "xx" }; const obj2 = { a: 2, b: "3", d: "hello" }; for (const key in obj1) { const _key = key as keyof typeof obj1; obj1[_key] = obj2[_key]; } x[_key] error Type 'string | number' is no ...

Tips for eliminating the page URL when printing a page using window.print() in JavaScript or Angular 4

Can someone help me with a function that uses window.print() to print the current page, but I need to remove the page URL when printing? I'm looking to exclude the URL from being printed and here is the code snippet where I want to make this adjustme ...

REDUX: The dispatch function is failing to update the store

Working on a project developing a chrome extension that involves dispatching functions in popup.tsx. However, the store does not update when I try to dispatch. Interestingly, the same code works perfectly fine in the background page. Any suggestions on wha ...

illustrating an embedded image within angular2

Currently tackling a project in Angular2, where the task involves loading an image directly from a database (base64 encoded). In Angular1, one could easily achieve this with the following code: <img data-ng-src="data:image/jpg;base64,{{entry.img}}" /&g ...

How do I remove a specific object from my localStorage array in Angular?

Currently, I am storing and retrieving form values from localStorage. When displaying the data, I want to be able to remove a specific object that is clicked on. The issue is that my current code removes all the data instead of just the selected object. Be ...

What is the best way to access static variables from the class(es) of an object in TypeScript?

I am seeking a way to access the static members of classes, including parent classes from which an object was created. Currently, I am adding each class to an array in the constructor as a workaround. However, with thousands of classes to define, I am hopi ...

The function "AAA" is utilizing the React Hook "useState" in a context that does not fit the requirements for either a React function component or a custom React Hook function

Upon reviewing this code snippet, I encountered an error. const AB= () => { const [A, setA] = useState<AT| null>(null); const [B, setB] = useState<string>('0px'); ..more} ...

Remove any extra spaces at the end of a copied number when using Angular

Is there a way to automatically remove spaces at the end of a 10-digit number when it is copied from another source (like email or Word documents) and pasted into the search bar? Currently, this function only works when we press enter. I would like for bl ...

What are the steps to publish an Electron application for Windows, Mac, or Linux operating systems?

After developing an App using Angular 2, I successfully created iOS and APK files with some modifications using Ionic. Now, I am looking to create a desktop app file for the same project. I have researched various resources on Electron but haven't f ...

The process of verifying a form array with constantly changing values through a form builder

In my current angular project, I am working on a form submission feature that dynamically adds rows to the form when the add button is clicked. Each row represents an exam with subject and mark fields, and it can also be deleted. As a requirement, I need ...

Guide on integrating a bearer token with an odata source in order to utilize it with a Devextreme dxData Grid

I am using Angular and I am attempting to pass a bearer token through an OData source with a DevExtreme DXDataGrid, but I am facing authentication issues. The error message "Current user did not login to the application!" keeps appearing, indicating that i ...

TypeScript setter failing to activate

Here is a snippet of code from a class called VibrationElement: export class VibrationElement { private _amplitude: number; get amplitude(): number { return this._amplitude; } set amplitude(amplitude: number) { console.lo ...

Issue: The JSX element 'X' is missing any constructors or call signatures

While working on rendering data using a context provider, I encountered an error message stating "JSX Element type Context does not have any constructor or call signatures." This is the code in my App.tsx file import { Context } from './interfaces/c ...

Angular Component Caching

I am currently working with two Angular components. The first component displays a list of picture items that are fetched from a server. When the user selects a picture, they are taken to the second page where additional information is shown in a detailed ...

Can one bring in a JavaScript function using webpack?

I have a unique JS library called: say-my-greeting.js function SayMyGreeting (greeting) { alert(greeting); } Now I want to incorporate this function in another (.ts) file; special-class.ts import SayMyGreeting from './say-my-greeting.js' ex ...

Issue with CanActivateChild not being processed

After logging out and navigating to /, I am facing an issue where the canActivateChild guards are not being executed to redirect to the login page. The main requirement is that none of the application should be accessible without first logging in. Below ...

Steer clear of type assertion in your codebase when utilizing useSelector alongside Redux, Immutable.js, and TypeScript

Currently, I am working with a combination of Redux, Immutable.js, and TypeScript. I am facing challenges in obtaining proper types from the useSelector hook, which is leading me to use type assertions. I acknowledge that this is not the best practice and ...

After the initialization of the app, make sure to provide an InjectionToken that includes the resolved configuration

During the initialization of the application, I am looking to retrieve the configuration using a factory that will be resolved through the APP_INITIALIZER provider. export function loadConfig(): () => Promise<Config> { // return promised confi ...

trouble with the layout of the table

Could you assist me in improving the design to enhance data clarity? Your help would be greatly appreciated. Thank you for your anticipated response. CSS File: table-layout: fixed; width: 100%; border-collapse: collapse; table-layout: fixed; ove ...

How do AppComponent and @Component relate to each other in AngularJs 2?

Recently, I came across the file app.component.ts in Example and found some interesting code. The link to the example is: here. Here's a snippet of the code: import { Component } from '@angular/core'; export class Hero { id: number; na ...