【发布时间】:2022-02-23 07:46:56
【问题描述】:
我可以将焦点设置到输入字段,但不能设置选择。我错过了什么?
这行得通:
<input matInput formControlName="name" required maxlength="100" id="elementFocus" appElementFocus="true" />
这不是
<mat-select formControlName="countryId" required id="elementFocus" appElementFocus="true">
这是现在存在的整个部分,当页面加载时,第二个表单元素(名称)具有焦点。我需要选择才能获得焦点。
<mat-card-content>
<div fxLayout="column" fxLayoutGap="25px" class="container">
<mat-form-field appearance="standard">
<mat-label>Countries</mat-label>
<mat-select formControlName="countryId" #countrySelectRef required>
<mat-option *ngFor="let c of countries" [value]="c.id"
>{{ c.name }}
</mat-option>
</mat-select>
<mat-error *ngIf="hasError(f.countryId)">{{
getErrorMessage(f.countryId)
}}</mat-error>
</mat-form-field>
<mat-form-field appearance="standard">
<mat-label>Name</mat-label>
<input matInput formControlName="name" required maxlength="100" />
<mat-hint align="end">{{ f.name.value.length }} / 100</mat-hint>
<mat-error *ngIf="hasError(f.name)">{{
getErrorMessage(f.name)
}}</mat-error>
</mat-form-field>
</div>
</mat-card-content>
.ts 代码(我认为缩小到所有相关的)。
@ViewChild(MatSelect) countrySelectRef: MatSelect;
constructor(
private formBuilder: FormBuilder,
private activatedRoute: ActivatedRoute,
private router: Router,
private matDialog: MatDialog,
private readonly countryService: CountryService,
private readonly stateService: StateService,
private messageService: UIMessageService) { }
ngOnInit(): void {
const paramId = this.getParam('id');
this.isAdd = !paramId
this.id = !paramId ? uuid() : paramId
this.heading = this.isAdd ? `Add ${this.headingName}` : `Edit ${this.headingName}`
this.initForm();
if (!this.isAdd) {
this.patchForm()
}
}
ngAfterViewInit(): void {
if (this.countrySelectRef) {
this.countrySelectRef.focus();
}
}
【问题讨论】:
-
你是说自动对焦吗?因为从您的代码来看,它看起来应该聚焦选择,但由于您没有在
mat-form-field指令中使用它,所以选择的样式不正确,因此,没有应用聚焦样式。 -
我真的想在这里弄明白你在说什么。我对 Angular 比较陌生,我无法让我的 .ts 后端文件真正弄清楚 #countryidForSelect 是什么。我已经给了 mat-select # 指令:
。但是我刚刚添加到 .ts ngOnInit 方法中的这一行不会编译。 if(this.countryidForSelect) this.countryidForSelect.focus(); -
@MishaMashina 不,这没有帮助,但这可能是因为我还不明白答案。谢谢你的指点。
-
向我们展示 TS 代码以及模板。模板中的
#countryIdForSelect称为模板变量,也称为局部引用,虽然您可以从组件(TS 文件)中访问它们,但您需要执行额外的步骤,您需要使用装饰器ViewChild。如果您分享您的 TS 代码,我们可以向您展示。