【问题标题】:Mat-AutoComplete in FormGroup CustomFilterFormGroup CustomFilter 中的 Mat-AutoComplete
【发布时间】:2018-11-28 10:39:08
【问题描述】:

我正在使用 Angular CLI。而且我想制作一个查看所有值的自动完成表单(不像 angular.io 的例子那样做“开始”)。

我设法使它与[formControl] 一起工作,但我想将它插入FormGroup。所以我认为将它与formControlName 一起使用(同时使用formControlName[formControl])意味着我没有从我的表单中获得价值。

这是我当前的代码,过滤器有问题。谢谢你的帮助

component.html

<form [formGroup]="tumeurForm" (ngSubmit)="onSubmitForm()">
  <mat-form-field appearance="outline">
    <mat-label>Diagnostic : inscription de la tumeur</mat-label>
    <input
      matInput 
      type="text" 
      formControlName="localisation"
      [matAutocomplete]="auto"/>
    <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
      <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
        {{ option }}
      </mat-option>
    </mat-autocomplete>
  </mat-form-field>
</form>

component.ts

export class DiagnosticDialogComponent implements OnInit  {

  options = [
    "(C00) Néoplasie maligne de la lèvre",
    "(C00.0) Lèvre supérieure, bord libre",
    "(C00.1) Lèvre inférieure, bord libre"
  ];

  patientid: string;
  public tumeurForm: FormGroup ;
  filteredOptions: Observable<string[]>;


  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.initForm();
    this.filteredOptions = this.tumeurForm.valueChanges.pipe(
      startWith(""), 
      map(val => this.filter(val))
    );
  }

  filter(val: string): string[] {
    return this.options.filter(option => {
      return option.toLowerCase().match(val.toLowerCase());
    });
  }

  initForm() {
    this.tumeurForm = this.formBuilder.group({
      localisation: ['', Validators.required]
    });
  }

  onSubmitForm() {
    const localisation = this.tumeurForm.get('localisation').value;
    const Patientid = this.patientid;
    const newDiagnostic = new Diagnostic(localisation, Patientid);
    this.diagnosticsService.CreateDiagnostic(newDiagnostic);
  }
}

【问题讨论】:

    标签: angular filter autocomplete angular-material


    【解决方案1】:

    (如果我理解正确的话)

    您正在FormGroup.valueChanges 进行管道传输。但是您需要在FormControl 上进行操作。

    所以不是

    this.filteredOptions = this.tumeurForm.valueChanges.pipe(
      startWith(""), 
      map(val => this.filter(val))
    );
    

    这样做:

    this.filteredOptions = this.tumeurForm.controls['localisation'].valueChanges.pipe(
      startWith(""), 
      map(val => this.filter(val))
    );
    

    【讨论】:

    • 在我的情况下,这种方式对我有用 this.filteredOptions = this.form.valueChanges.pipe( startWith(""), map(val => this.filter(val)) );完成了!
    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2018-09-16
    • 2019-10-27
    • 2021-07-04
    • 2020-11-07
    相关资源
    最近更新 更多