我可以將焦點設定到輸入欄位,但不能設定選擇。我錯過了什么?
這有效:
<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();
}
}
uj5u.com熱心網友回復:
您的代碼有問題,從某種意義上說它可能會觸發ExpressionChangedAfterItHasBeenCheckedError錯誤,但即使出現該錯誤,它也應該可以正常作業。您的代碼和評論中描述的錯誤訊息不匹配,可能表明問題出在其他地方。
我確實提供了一個替代方案,希望它能解決您的問題。您需要將 添加A11yModule到imports宣告使用該模板的組件的模塊陣列中。
模板
<mat-form-field appearance="standard" cdkMonitorSubtreeFocus>
<mat-label>Countries</mat-label>
<mat-select formControlName="countryId" #countrySelectRef required
cdkTrapFocusAutoCapture
cdkTrapFocus="false">
<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>
請注意添加的 2 個(總共 3 個輸入)指令:
- cdkMonitorSubtreeFocus:如果元素或其任何子元素被聚焦,則認為該元素已聚焦
- cdkTrapFocusAutoCapture:指令是否應該在初始化時自動將焦點移動到被困區域,并在銷毀時將焦點回傳到前一個 activeElement。
- cdkTrapFocus="false":如果此值為真,它將無限期地將焦點困在該指令上。
參考:材料檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/431276.html
