Search code examples
angulardrop-down-menuangular-reactive-formscascadingdropdown

Cascade Dropdown in Angular Reactive Form


For the cascading dropdown, On changing the country, the state value must be reset.
How can i achieve that ?
This is what i did
demo


Solution

  • I leave you HERE your fork working as you need.

    All you have todo do is subscribe to the changes of the 'Country' field with valueChanges, something like what I do here with the formFieldCountryValueChanges$ Observable:

    private formFieldCountryValueChanges$: Observable<any>;
    
    ngOnInit() {
        this.myForm = this.formBuilder.group({
          Country: ['', [Validators.required]],
          State: ['', [Validators.required]],
        });
    
        this.countries = this.selectService.getCountries();
    
        this.formFieldCountryValueChanges$ = this.myForm
          .get('Country')
          .valueChanges.pipe(
            tap((_arrayStates) => {
              this.myForm.patchValue({ State: '' });
              return _arrayStates;
            })
          );
        this.formFieldCountryValueChanges$.subscribe();
      }