如何聚焦具有 ngif 的文本区域

Mau*_*rez 2 angular

我有以下 Angular 2 组件,我需要textareawith idbannernote在可见时立即聚焦 ( isEditEnabled)

<div class="cont-notesbanner">
  <p class="triangle"></p>
  <h3 class="tit-notesbanner">Add notes:</h3>

  <form (ngSubmit)="onSubmit(f)" #f="ngForm">
    <p
      class="p-notesbanner"
      *ngIf="!isEditEnabled"
      [ngClass]="currentAsset.notes.length === 0 ? 'it-place' : ''"
    >
      {{ currentAsset.notes.length === 0 ? "Add notes" : currentAsset.notes }}
    </p>
    <textarea 
      rows="4"
      cols="50"
      *ngIf="isEditEnabled"
      class="txt-notesbanner"
      name="bannernote"
      id="bannernote"
      rows="10"
      [(ngModel)]="currentAsset.notes"
      #bannernote
      onload="$('#bannernote').focus();"
    ></textarea>

    <div class="txt-right">
      <a class="smallButton" (click)="onCloseBannernotes()">Cancel</a>
      <a
        class="smallButton"
        (click)="onEditBannernotes()"
        *ngIf="!isEditEnabled"
        >Edit</a
      >
      <button type="submit" class="smallButton" *ngIf="isEditEnabled">
        Accept
      </button>
    </div>
  </form>
</div>
Run Code Online (Sandbox Code Playgroud)

我尝试使用“onshow”和“onload”事件来实现这一点,正如您在上面看到的那样,但没有成功

我还在这个方法中添加了代码,每当按钮从“编辑”切换到“接受”时就会调用该代码,例如document.getElementById("bannernotes").focus 但这不起作用,因为当被调用时该元素尚未渲染,因为 ngif 尚未被“被处决”

onEditBannernotes() {
  this.isEditEnabled = !this.isEditEnabled;
}
Run Code Online (Sandbox Code Playgroud)

Con*_*Fan 5

您可以使用 访问代码中的元素@ViewChild。由于该元素最初可能不可用,因此将关联的属性定义为setter,并在其中设置焦点。正如@Stefan在评论中建议的,首先检查元素引用是否已定义;undefined当元素从视图中删除时就会变成这样。

// Set the focus on the textarea as soon as it is available
@ViewChild("bannernote") set bannerNoteRef(ref: ElementRef) {
  if (!!ref) {
    ref.nativeElement.focus() ;
  }
}
Run Code Online (Sandbox Code Playgroud)

请参阅此 stackblitz的演示。

  • 为 ref 添加 nullcheck,否则如果经常切换它可能会抛出错误。示例:https://stackblitz.com/edit/angular-2bbm7u (2认同)