html - hide 设置为 false 后聚焦输入

标签 html jquery angular typescript

因此,在单击编辑按钮后,我尝试将注意力集中在输入上。 edit 会将 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,因此我专注于输入的逻辑将不起作用。有没有办法集中输入

enter image description here

On click of edit button the cursor should focus on the input field

最佳答案

问题是你需要给 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()
      })
    }
  }

关于html - hide 设置为 false 后聚焦输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61453821/

相关文章:

html - 什么时候视口(viewport)不是矩形的

javascript - 使用jquery访问下拉菜单

css - 当文本嵌套在大约 5 个生成的 DIV 标签中时,将文本获取到 "display:inline"的简单方法?

html - 从 Google Images 在 R 中抓取网页

jquery - 如何自定义下拉菜单

jquery - Windows 7 浏览器忽略 DIV 高度 100%

java - 在JHipster中添加静态页面

javascript - 如何将数据从响应对象分配给对象

angular - ContentChildren 类选择器

javascript - 如何使用 jquery 转到顶部 onClick 函数?