簡體   English   中英

如何檢測何時在Angular中渲染視圖元素?

[英]How to detect when a view element is rendered in Angular?

我的設置是帶有可單擊行的Angular Material數據表。 單擊某行時,其內容將在文textarea聯顯示以供編輯。 我唯一的問題是,我嘗試將輸入焦點移至所示的textarea 我嘗試使用@ViewChild進行此操作,但是稍后會在單擊處理程序已經執行時填充它。

一些代碼,以說明:

app.component.ts:

import {Component, ElementRef, ViewChild} from '@angular/core';

@Component({ selector: 'app-root', templateUrl: './app.component.html' })
export class AppComponent {
  columns = ['id', 'def'];
  selected: string;
  ruleDef: string;
  @ViewChild('edit') editArea: ElementRef;
  selectRule(rule: Rule) {
    this.selected = rule.id;
    if (this.editArea) this.editArea.nativeElement.focus();
  }
}

interface Rule {id: string, def: string}

app.component.html:

<mat-table #table [dataSource]="dataSource">
  <ng-container matColumnDef="id">
    <mat-header-cell *matHeaderCellDef>Rule ID</mat-header-cell>
    <mat-cell *matCellDef="let element">{{element.id}}</mat-cell>
  </ng-container>
  <ng-container matColumnDef="def">
    <mat-header-cell *matHeaderCellDef>Rule Definition</mat-header-cell>
    <mat-cell *matCellDef="let element">
      <mat-form-field *ngIf="element.id === selected">
        <code><textarea matInput [(ngModel)]="ruleDef" #edit></textarea></code>
      </mat-form-field>
      <code *ngIf="element.id !== selected">{{element.def}}</code>
    </mat-cell>
  </ng-container>
  <mat-header-row *matHeaderRowDef="columns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: columns;" (click)="selectRule(row)"></mat-row>
</mat-table>

selectRule()函數中, editAreaundefined ,或指向先前選擇的行。 顯然, selectRule()是放置焦點更改的地方,但是我在Angular中找不到合適的事件處理程序。

在設置焦點之前,您必須等待區域穩定。

可以使用與角形材料中相同的方法來完成:

import {take} from 'rxjs/operators/take';

constructor(private zone: NgZone) { }

selectRule(rule: Rule) {
  this.selected = rule.id;

  this.zone.onMicrotaskEmpty.asObservable().pipe(
      take(1)
    )
    .subscribe(() => {
      this.editArea.nativeElement.focus();
    });
}

Ng運行示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM