从Angular Form获取自动完成表单数据

时间:2019-06-14 15:34:34

标签: angular

使用Angular 8material。使用reactive形式。我可以使用formControl来获取所有其他字段,但自动完成字段除外。

  <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));
    }
  }

}

analysisDescription属性始终为空。我什至尝试将formControlName="analysisDescription"放在mat-autocomplete div上,而不是<input>上,我只在form.value上得到空值

1 个答案:

答案 0 :(得分:2)

您正在通过同时使用formControlName="analysisDescription"[formControl]="myControl"将两个表单控件与您的输入相关联。很明显[formControl]="myControl"处于优先地位。您应该删除[formControl]="myControl"并使用已定义的现有控件  在this.form.controls.analysisDescription.valueChanges表单生成器中也可以自动完成。