ค้นหาเว็บไซต์

javascript - วิธีตั้งค่าโฟกัสอัตโนมัติใน mat-select?


ในโปรเจกต์ Angular ของฉันมี Angular Material และใช้ mat-select. Mat-select เป็นองค์ประกอบแรกสำหรับฟอร์มของฉัน ในกรณีของฉันจะตั้งค่าโฟกัสอัตโนมัติเมื่อหน้าโหลดสำเร็จ แต่ฉันไม่สามารถตั้งค่าโฟกัสอัตโนมัติบน mat-select ได้ มีใครสามารถช่วยฉันหาวิธีตั้งค่าโฟกัสอัตโนมัติใน mat-select ได้ไหม

@ViewChild("name") nameField: ElementRef;

ngOninit() {
  this.nameField.nativeElement.focus();
} 

เอชทีเอ็มแอล

<div>
 <mat-select [(ngModel)]="nameField" #name>
    <mat-option *ngFor="let option of options2" [value]="option.id">
      {{ option.name }}
    </mat-option>
 </mat-select>
</div>

คำตอบ #1

HTML :

<mat-select #someRef >
    <mat-option *ngFor="let item of items;" [value]="item">
    {{item.name}}
    </mat-option>
</mat-select>

.ts : ตรวจสอบให้แน่ใจว่าคุณนำเข้า MatSelect

import { MatSelect } from '@angular/material';
@ViewChild('someRef') someRef: MatSelect;


ngOnInit() {
    if(this.someRef) this.someRef.focus();
}

หวังว่านี่จะช่วยได้นะ

คำตอบ #2

ถ้าฉันเข้าใจถูกต้อง คุณต้องการให้โฟกัสที่ element แบบ select เมื่อโหลดหน้า ถ้าเป็นกรณีนี้ โค้ดของคุณก็สมบูรณ์แบบแล้ว แค่คุณต้องย้ายตรรกะการโฟกัสไปไว้ในเหตุการณ์วงจรชีวิตอื่นซึ่งคือ

ngAfterViewInit

HTML :

<mat-select #fff>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
</mat-select>

TS :

export class SelectOverviewExample  implements AfterViewInit{
  foods: Food[] = [
    {value: 'steak-0', viewValue: 'Steak'},
    {value: 'pizza-1', viewValue: 'Pizza'},
    {value: 'tacos-2', viewValue: 'Tacos'}
  ];

  @ViewChild("fff", {static: false}) nameField: ElementRef;

  ngAfterViewInit() {
    this.nameField.focused = true;
  }
}

ค้นหาตัวอย่างการทำงานที่นี่ คุณสามารถเห็นว่า select ถูกเน้น แสดงความคิดเห็นโค้ดภายใน ngAfterViewInit() แล้วดูความแตกต่างนี้

บทความที่เกี่ยวข้อง