【问题标题】:How to Focus a TextArea that has an ngif如何聚焦具有 ngif 的 TextArea
【发布时间】:2019-06-30 15:05:48
【问题描述】:

我有以下 Angular 2 组件,我需要 ID 为 bannernotetextarea 在可见后立即聚焦 (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>

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

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

onEditBannernotes() {
  this.isEditEnabled = !this.isEditEnabled;
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    您可以使用@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() ;
      }
    }
    

    请参阅this stackblitz 以获取演示。

    【讨论】:

    • ref添加一个nullcheck,否则如果你经常切换它可能会抛出一个错误。示例:stackblitz.com/edit/angular-2bbm7u
    • @Stefan - 感谢您的评论!我做了更正。
    • @MauricioGraciaGutierrez - 你不喜欢!!ref?它比ref !== undefined 更安全。
    • 我是 Angular 的菜鸟(您可能已经猜到了),请随意撤销编辑;-)
    【解决方案2】:

    使用 @ViewChild() 装饰器检索您的 textearea 元素。 在您的文本区域上放置一个标识符,如下所示:&lt;textarea #myTextarea&gt;&lt;/textarea&gt;

    别忘了实现 AfterViewInit 接口。

     @ViewChild('myTextarea') textArea;
    
     ngAfterViewInit() {            
        this.textArea.focus();
     }
    

    【讨论】:

    • 我刚试过这个ERROR TypeError: Cannot read property 'focus' of undefined
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多