garg10may
garg10may

Reputation: 6179

Get Autocomplete form data from Angular Form

Using Angular 8 and material. Using reactive form. I am able to get all other fields using formControl except the autocomplete one.

  <mat-form-field>
      <input type="text"
      formControlName="analysisDescription" 
      placeholder="Analysis Description"
      matInput [formControl]="myControl"
      [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
          {{option}}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field>

.Ts

export class PreTflFormComponent implements OnInit {

  myControl = new FormControl();
  public ADNames: any;
  filteredOptions: Observable<string[]>;
  form: FormGroup;
  public meetingId: number;


  constructor(
    private fb: FormBuilder,
    public dialogRef: MatDialogRef<PreTflFormComponent>,
    private httpClient: HttpClient,
    private genericService: GenericService,
    private srapiService: SrapiService
  ) {

    this.form = fb.group({
      analysisDescription: [null],
      emails: [null, Validators.required]
    });
  }

  ngOnInit() {
    this.genericService.getADNames().subscribe(data => {
      this.ADNames = data;

      this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );

    });

  }

  private _filter(value: string): string[] {

    if (value.length > 1) { 
      const filterValue = value.toLowerCase();
      return this.ADNames.filter(option => option.toLowerCase().includes(filterValue));
    }
  }

}

The analysisDescription property is always null. I even tried putting formControlName="analysisDescription" on mat-autocomplete div rather than <input> one, I get null only in form.value

Upvotes: 0

Views: 1874

Answers (1)

ysf
ysf

Reputation: 4844

You are associating two form controls with your input by using formControlName="analysisDescription" and [formControl]="myControl" at the same time. and obviously [formControl]="myControl" is taking precedence. you should remove [formControl]="myControl" and use alredy existing control defined in form builder as this.form.controls.analysisDescription.valueChanges for auto complete as well.

Upvotes: 2

Related Questions