Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofocus only works once

When the Input is clicked, autofocus works only on the first instance - therefore the 'list-formatter' (autocompleListFormatter) is initiated only once.

**Demo**

Is there a simple solution to make 'autofocus' focus more than one time?

dropdown.component.html

<form [formGroup]="myForm" class="">
  <div class="form-style">
    <input
      autofocus
      [list-formatter]="autocompleListFormatter"
      type="text"
      class="form-control"
      ngui-auto-complete
      formControlName="costCenter"
      [source]="dropdownData"
      value-property-name="id"
      display-property-name="name"
      [(ngModel)]="value"
    />
  </div>
</form>

dropdown.component.ts

export class DropdownComponent implements OnInit, AgEditorComponent {
  @Input() name: String;

  public dropdownData = ColumnData[0].cellEditorParams.values;
  public myForm: FormGroup;
  public selected;
  value: any;
  oldValue: any;
  params: any;
  public container;
  constructor(private builder: FormBuilder, private _sanitizer: DomSanitizer) {}

// ****DROPDOWN****** //
  autocompleListFormatter = (data: any) => {
    let html = `<span>${data.name}</span>`;
    return this._sanitizer.bypassSecurityTrustHtml(html);
  };

  refresh(params: ICellEditorParams) {
    this.params.api.refreshCells();
    return true;
  }

  getValue(): any {
    if (this.value === '') {
      this.value = this.oldValue;
    }
    return this.value;
  }

  agInit(params: ICellEditorParams) {
    this.value = params.value;
    this.oldValue = this.value;
    this.value = '';
    return this.value;
  }

  ngOnInit() {
    this.myForm = this.builder.group({
      costCenter: ''
    });
  }
}

STACKBLITZ

Update: I have read that it is useful to implement an auto-focus directive. I have added the directive to my code but cannot get it to function correctly

like image 995
Ana_30 Avatar asked Sep 18 '19 09:09

Ana_30


1 Answers

this can be done without directive just get input elemnt refrence and run focus method

template

<form [formGroup]="myForm" class="">
  <div class="form-style">
    <input
      defFocus
      [list-formatter]="autocompleListFormatter"
      type="text"
      class="form-control"
      ngui-auto-complete
      formControlName="costCenter"
      [source]="dropdownData"
      value-property-name="id"
      display-property-name="name"
      [(ngModel)]="value"
      #agInput
    />
  </div>
</form>

component

export class DropdownComponent implements OnInit, AgEditorComponent {

  @Input() name: String;
  @ViewChild('agInput', { static: true}) public elm: ElementRef;

  ....

  setFocus() {
    this.el.nativeElement.focus();
  }

   ngAfterViewInit() {
     setTimeout(() => {
        this.setFocus();
     }, 500);
   }
}

demo 🚀

check my answer 👉 here where I create a custom directive to fix focus problem.

like image 193
Muhammed Albarmavi Avatar answered Sep 25 '22 18:09

Muhammed Albarmavi