rumblefx0
rumblefx0

Reputation: 673

Mat-autocomplete either doesn't bind or validate

I'm working on an Angular6 application with Material Design and ReactiveForms and I'm having some trouble getting validation/binding to work on a Material auto-complete control.

As far as i know, i need the [formControl] to bind my values and the formControlName='countryid' in combination with required attribute for reactiveforms validation.

The problem is, I can either get the lookup to work OR the validation but not both for some reason. I'm pretty sure this has to do with the mentioned attributes and the underlying binding, but I just don't see the problem. I tried different combinations and workarounds but to no avail.

Does anyone see where I messed up? Thanks in advance.

Stackblitz here: https://stackblitz.com/edit/angular-xhekyg

Upvotes: 0

Views: 1551

Answers (1)

Marshal
Marshal

Reputation: 11101

There were several imports missing from your app.module.ts in the stackblitz that had to be resolved before I could review.

I also am not sure what was in app.component.html so I commented it out and just called the <m-add-place></m-add-place> selector there as I believe that is what you wanted someone to look into.


Your first issue is [formControl]="countryAutoCompleteControl" formControlName="countryid"...

those both are FormControls and you are essentially assigning two FormControls to the same input.

  • countryAutoCompleteControl is a standalone FormControl created as a class variable.
  • countryid is a FormControl within the addPlaceForm

I started by removing [formControl]="countryAutoCompleteControl" as you don't need it. I also removed required from your input as it is also not needed... you already have required here countryid: ['', Validators.required]

<input matInput formControlName="countryid" type="text" placeholder="Pick one"
       aria-label="Number" [matAutocomplete]="auto">

In your ngOnInit change it to this to do the same thing.. only using countryid from your addPlaceForm

 // this.countryAutoComplete = this.countryAutoCompleteControl.valueChanges.pipe(
     this.countryAutoComplete = this.addPlaceForm.get('countryid').valueChanges.pipe(

Stackblitz

https://stackblitz.com/edit/angular-qy4nrm?embed=1&file=src/app/addplace/addplace.component.ts

Upvotes: 1

Related Questions