【问题标题】:Focus on input after hidden is set as false隐藏后专注于输入设置为false
【发布时间】:2020-08-10 17:01:35
【问题描述】:

所以我在点击编辑button 后试图专注于inputedit 会将 hidden 设置为 false。为此,我尝试了以下代码

editMyLink(i, currentState) {
    if (currentState == 'noEdit') {
      this.myLinkBody[i].value = this.myLinkBodyOriginal[i].value
      this.myLinkBody[i].currentState = 'edit';
      this.myLinkBody[i].buttonClass = "editButton"
    }
    else {
      this.myLinkBody[i].currentState = 'noEdit';
      this.myLinkBody[i].buttonClass = "noEditButton"
      let selector = '.myLinkEditInput:eq(' + i + ')'
      $(selector).focus()
    }
  }
<span *ngFor="let body of myLinkBody;let i=index;let last=last;" class="myLinkBody" [class.myLinkBodyLast]="last">
  
  <input class="myLinkEditInput" type="text" (keydown.enter)="saveMyLink(i)" [hidden]="body.currentState=='edit'" [(ngModel)]="body.value"/>
  
  <a [hidden]="body.currentState=='noEdit'"[href]="domainURL+body.href">{{body.value}}</a>
  
  <div id="editLinkButton"><a [class]="body.buttonClass" (click)="editMyLink(i,body.currentState)"></a></div>
  
  <div id="deleteLinkButton"><a (click)="deleteMyLink(i)"></a></div>

</span>

我意识到 hidden 只有在函数执行后才会变为 true,因此我专注于输入的逻辑将不起作用。有没有办法专注于输入

【问题讨论】:

    标签: html jquery angular typescript


    【解决方案1】:

    问题是你需要给 Angular “喘口气”——首先 Angular 必须显示输入,然后在你关注它之后——所以你使用 setTimeout。在 Angular 中,您可以使用模板引用变量,而不是使用 jQuery 来获取选择器,所以

    <input #valueID ... [hidden]="body.currentState=='edit'" [(ngModel)]="body.value"/>
      ...
    <!--see you pass the reference variable-->
    <a [class]="body.buttonClass" (click)="editMyLink(i,valueID,body.currentState)"></a>
    ..
    
    editMyLink(i,editID currentState) {
        if (currentState == 'noEdit') {
          this.myLinkBody[i].value = this.myLinkBodyOriginal[i].value
          this.myLinkBody[i].currentState = 'edit';
          this.myLinkBody[i].buttonClass = "editButton"
        }
        else {
          this.myLinkBody[i].currentState = 'noEdit';
          this.myLinkBody[i].buttonClass = "noEditButton"
          //here the "breath", well, the setTimeout
          setTimeout(()=>{
             editID.nativeElement.focus()
          })
        }
      }
    

    【讨论】:

    • 是的,它奏效了。但在我在选择器之前使用while 循环while(selector[0].hidden){} 之前。它不起作用,页面挂起,因为它是一个无限循环。为什么会这样?
    • 抱歉,我看不到“while”。无论如何,如果你想每次只编辑一个字段,我建议你使用一个辅助变量(例如 indexSelected),它等于“索引”,而不是“主体”的属性(最初等于 -1)跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2014-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多