Dog*_*027 2 javascript typescript angular-material 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}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
在selectRule()函数中,editArea是undefined或指向先前选择的行。显然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();
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1315 次 |
| 最近记录: |