我的设置是一个带有可点击行的Angular Material数据表。单击某行时,其内容将以<script>
var app = angular.module('app', []);
app.controller('myController', ['$scope', function($scope) {
$scope.Language = 'Hindi';
$scope.Preference = function(lang) {
$scope.Language = lang;
};
$scope.Preference1 = function(lang, lang1) {
$scope.Language = lang;
$scope.Language1 = lang1;
};
}]);
</script>
<h2>Attach functions or behavior with arguments - AngularJS</h2>
<div ng-app="app" ng-controller="myController">
Click
<button ng-click="Preference('English')">English</button>
<button ng-click="Preference('Hindi')">Hindi</button>
<button ng-click="Preference('Spanish')">Spanish</button>
<button ng-click="Preference1('French', ' and Hindi language also.')">French</button>
<p>I like {{ Language}} language {{ Language1 }} </p>
</div>
内嵌显示以进行编辑。我唯一的问题是,我尝试将输入焦点移到显示的textarea
。我尝试使用textarea
来完成它,但是当点击处理程序已经执行时,它会在以后填充。
一些代码,用于说明:
app.component.ts:
@ViewChild
app.component.html:
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}
在<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
是一个错误的位置,可以将焦点更改为,但我在Angular中找不到合适的事件处理程序
答案 0 :(得分: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 强>