如何检测何时在Angular中呈现视图元素?

问题描述 投票:2回答:1

我的设置是一个带有可点击行的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()函数中,editArea要么是undefined,要么指向之前选择的行。显然selectRule()是一个错误的地方,把焦点改变,但我找不到一个适当的事件处理程序在Angular

javascript angular typescript angular-material
1个回答
4
投票

在设置焦点之前,您必须等待区域稳定。

它可以与角材料中使用的方式相同:

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-run Example

© www.soinside.com 2019 - 2024. All rights reserved.