angular / components

Component infrastructure and Material Design components for Angular
https://material.angular.io
MIT License
24.24k stars 6.7k forks source link

bug(MatAutocomplete): MatAutocomplete + FormControl does not clear input correctly after option selection #25809

Open edsanchez-google opened 1 year ago

edsanchez-google commented 1 year ago

Is this a regression?

The previous version in which this bug was not present was

No response

Description

See example: https://material.angular.io/components/chips/examples#chips-autocomplete

In this example, after selecting an autocomplete option, we want to create a new chip and clear the typed text in the input element. The input is bound to a FormControl instance, so it should be possible to clear the input by simply calling this.fruitCtrl.setValue(null) or this.fruitCtrl.setValue(''). Instead, the previously typed text remains visible, but if you subscribe to the FormControl.valueChanges property you will see the new empty value emitted correctly.

The example works around this issue by accessing the native input element and updating the value directly.

Reproduction

Steps to reproduce:

  1. See example https://material.angular.io/components/chips/examples#chips-autocomplete
  2. Remove the nativeElement reference
  3. Input text remains visible despite the FormControl instance correctly emitting the new value, creating an inconsistent state

Expected Behavior

It should be enough to just update the FormControl to ensure the input element has the correct value set.

Actual Behavior

The input element is left in an inconsistent state unless the user manually updates the native element's value directly.

Environment

mario-d-s commented 1 year ago

I'd like to add some weight on this because I have a very similar problem. I also want to use the FormControl.setValue function to set the text of an autocomplete element - an actual value instead of clearing it.

This unfortunately does not work and I have to jump through hoops to get at the native input element, which is of course counter to the spirit of a framework like Angular.

Previous bug reports have always gone stale, unfortunately: #22985, #22914, #18286 (explained poorly but probably the same). This is very much an issue...

MikaStark commented 8 months ago

Same for me.

To workaround this issue, I use MatChipInput#clear method instead of direct use of nativeElement. IMO it's less "tricky".

// ...

@ViewChild('fruitChipInput') fruitChipInput: MatChipInput;

// ...

selected(event: MatAutocompleteSelectedEvent): void {
  this.fruits.push(event.option.viewValue);
  this.fruitChipInput.clear();
  this.fruitCtrl.setValue(null);
}
anasbud commented 3 weeks ago

In Angular 17, still got the issue. Any update on that ?

selectUser(user: User) {
    this.selectedUser.set(user);
    this.form.controls.name.setValue("");
}

The input is not cleared.