Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug(MatAutocomplete): setValue on FormControl does not update AutoComplete Input #29063

Closed
1 task
ChazUK opened this issue May 16, 2024 · 4 comments
Closed
1 task
Labels
needs triage This issue needs to be triaged by the team

Comments

@ChazUK
Copy link

ChazUK commented May 16, 2024

Is this a regression?

  • Yes, this behavior used to work in the previous version

The previous version in which this bug was not present was

No response

Description

When using a custom input field with a FormControl, I am unable to dynamically set the value of the input element via setValue().

https://stackblitz.com/edit/vavcrk

Reproduction

https://stackblitz.com/edit/vavcrk

Expected Behavior

Using setValue() on the FormControl should update the value of the input element.

Actual Behavior

Input element value continues to be empty

Environment

  • Angular: 17
  • CDK/Material: 16
  • Browser(s): Chome
  • Operating System (e.g. Windows, macOS, Ubuntu): MacOS
@ChazUK ChazUK added the needs triage This issue needs to be triaged by the team label May 16, 2024
@ChazUK
Copy link
Author

ChazUK commented May 17, 2024

Just to clarify I want to update the query string that goes into the matInput field dynamically in code.

@lsamboretrorabbit
Copy link
Contributor

Since you are working with an Autocomplete that expects a User object or a string that represents the user's name.

By updating your test function to something similar to below. You will then be able to dynamically set your FormControl

test() {
    this.myControl.setValue({ name: 'HELLO' });
  }

@ChazUK
Copy link
Author

ChazUK commented May 20, 2024

@lsamboretrorabbit that's the bit where maybe I'm getting a bit confused. I don't want to update the selected value, I want to update the query value that will be used to derive the autocomplete options. And from what I can tell there isn't a way to be able to do that.

Also the FormControl typing is set to string | User which would make me think I can update it with a string and it still search.

@crisbeto
Copy link
Member

The reason your example doesn't work is because the display function expects only a User, but your value is User | string. It works if you change it to this:

displayFn(user: User | string): string {
    if (typeof user === 'string') {
      return user;
    }

    return user && user.name ? user.name : '';
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
needs triage This issue needs to be triaged by the team
Projects
None yet
Development

No branches or pull requests

3 participants