Update “autofocus” attribute via interaction on template level in angular

后端 未结 2 1725
梦毁少年i
梦毁少年i 2021-01-14 14:35

Having a problem regarding the autofocus attribute in cooperation with Angular. In detail I have a

with an
相关标签:
2条回答
  • 2021-01-14 15:09

    If you check in the development tools (F12 tools), you will see that the new input control actually gets the autofocus attribute, but it does not get the focus. That is because autofocus sets the focus on an element when the page loads. In your case, the page is already loaded when the new element becomes visible.

    What you can do instead is to set the focus programmatically on the new input element. In order to do that, you can define a common template reference variable for the two input elements having an ngIf condition:

    <input #inputElement *ngIf="selection === 1"
          [(ngModel)]="myForm.secondInpElem"
          name="secondInpElem"
          placeholder="secondInpElem">
    
    <input #inputElement *ngIf="selection === 2"
            [(ngModel)]="myForm.thirdInpElem"
            name="thirdInpElem"
            placeholder="thirdInpElem">
    

    and monitor the presence of these elements with ViewChildren and the QueryList.changes event. Each time one of the input element becomes visible, you set the focus on it:

    @ViewChildren("inputElement") inputElements: QueryList<ElementRef>;
    
    ngAfterViewInit() {
      this.inputElements.changes.subscribe(() => {
        this.inputElements.last.nativeElement.focus();
      });
    }
    

    See this stackblitz for a demo.

    0 讨论(0)
  • 2021-01-14 15:11

    Another option is hide the inputs (not use *ngIf else display.style) and reference variables see https://stackblitz.com/edit/angular-sbc4pp?file=src%2Fapp%2Fapp.component.html

        <label>
          <input [ngModel]="selection" (change)="change(second,1)" 
                 name="radioInpElem"
                 type="radio"
                 [value]="1"> 
                 Option 1
        </label>
        <br>
        <label>
          <input [ngModel]="selection" (change)="change(third,2)"
                 name="radioInpElem"
                 type="radio"
                 [value]="2">
                 Option 2
        </label>
    
      <input #second [style.display]="selection===1?'inherit':'none'"
            [(ngModel)]="myForm.secondInpElem"
            name="secondInpElem"
            placeholder="secondInpElem">
    
      <input #third [style.display]="selection===2?'inherit':'none'"
              [(ngModel)]="myForm.thirdInpElem"
              name="thirdInpElem"
              placeholder="thirdInpElem">
    

    Your function change like

      change(element:any,index:number)
      {
      this.selection=index;
      setTimeout(()=>{element.focus()},0);
      }
    
    0 讨论(0)
提交回复
热议问题