gpt4 book ai didi

javascript - 如何检测 View 元素何时在 Angular 中呈现?

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:28 24 4
gpt4 key购买 nike

我的设置是一个带有可点击行的 Angular Material 数据表。单击一行时,其内容将内联显示在 textarea 中以供编辑。我唯一的问题是,我尝试将输入焦点移动到显示的 textarea。我尝试使用 @ViewChild 执行此操作,但稍后会在点击处理程序已执行时对其进行填充。

一些代码,用于说明:

应用程序组件.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}

应用程序组件.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 中找不到合适的事件处理程序

最佳答案

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

它可以像在有 Angular Material 中使用的方法一样完成:

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

关于javascript - 如何检测 View 元素何时在 Angular 中呈现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49036289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com