Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mat-AutoComplete in FormGroup CustomFilter

I am using Angular CLI. And I want to make an autocomplete form that looks in all values ​​(unlike the example of angular.io that does a "start with").

I managed to make it work with [formControl] but I want to insert it into a FormGroup. So I think using it with formControlName (using formControlName and [formControl] at the same time) meant that I did not get the value from my form.

Here is my current code with a problem on the filter. Thank you for your help

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);
  }
}
like image 752
Newbiiiie Avatar asked Jun 19 '18 12:06

Newbiiiie


1 Answers

(if I understood the problem correctly)

You are piping at the FormGroup's .valueChanges. But you need to do it on the FormControl.

So instead of

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

do this:

this.filteredOptions = this.tumeurForm.controls['localisation'].valueChanges.pipe(
  startWith(""), 
  map(val => this.filter(val))
);
like image 156
Martin Schneider Avatar answered Sep 27 '22 17:09

Martin Schneider