Search code examples
htmlangulartypescriptfocus

Clearing Datalist with (focus) not working in Angular


I have a datalist to make a selection, which works fine. However, I want the text inside the input to clear when the user clicks back on it. Right now the text remains and has to be manually erased to see the original list. example

I am using Angular 12. I am trying to use the focus to do this. Here is my HTML:

 <input type="text" list="clinics" class="form-control" formControlName="preferredClinic" (focus)="clearPreference()" placeholder="Search...">
 <datalist id="clinics">
      <option value="Unsure/No preference"></option>
      <option *ngFor="let clinic of clinicList" [value]="clinic">{{clinic}}</option>
 </datalist>

and this is the function:

  clearPreference(){
    this.formValue.value.preferredClinic = "";
    console.log("This has gained focus");
  }

The console logging works, so I know the (focus) is triggering, but it isn't clearing the input field. Any idea what I'm doing wrong?


Solution

  • try use this: this.formValue.controls.preferredClinic.setValue(''); or

    this.formValue.setValue({ preferredClinic: '' });