【问题标题】:Focus a specific mat-option item when mat-select dialog is opened?打开 mat-select 对话框时聚焦特定的 mat-option 项?
【发布时间】:2020-04-29 08:30:59
【问题描述】:

我想在 mat-select 打开时自动聚焦到一个选项(滚动到一个选项)。我认为通过一些搜索可以轻松解决这个问题,但我无法在任何地方找到可靠的答案。

这是我使用的垫选择。

             <mat-select required name="AngabeId" [(ngModel)]="bedingungszielList[0]?.BedingungenList[i].AngabeId">
                <ng-container *ngFor="let antragsbereich of antragsBereichListWithAngabelist">
                  <mat-optgroup *ngIf="antragsbereich.AngabeList.length > 0" [label]="antragsbereich.Bezeichnung" class="bedigungOptGroup">
                    <ng-container *ngFor="let angabe of antragsbereich.AngabeList">
                      <mat-option *ngIf="angabe.Id !== Id" [value]="angabe.Id" class="bedigungOptions">
                        {{ angabe.Fragetext }}
                      </mat-option>
                    </ng-container>
                  </mat-optgroup>
                </ng-container>
              </mat-select>

这是我想要实现的一些示例代码,angabe.Id 是 mat-option ngmodel。

  this.antragsBereichListWithAngabelist.forEach(element => {
    element.AngabeList.forEach(angabe => {
       if(angabe.Id===962)
         angabe.Id.focus(); // mat-option focus, my intention, sample code(bad)
    });
  });

这是带有图像的示例: mat-option focus

【问题讨论】:

  • 试试&lt;mat-select ... [(value)]="yourFunction()" ...&gt;
  • 你能详细说明吗?

标签: html angular typescript angular-material select-options


【解决方案1】:

如果我了解您的问题,您希望在打开选择框时关注一个选项。所以,我建议你在 mat-select 中使用(打开的)事件。这是我尝试过的:

.html

<mat-form-field>
  <mat-label>Cars</mat-label>
  <mat-select [(ngModel)]="default" required (opened)="selectOpened()">
    <mat-option value="volvo">Volvo</mat-option>
    <mat-option value="saab">Saab</mat-option>
    <mat-option value="mercedes">Mercedes</mat-option>
    <mat-option value="audi">Audi</mat-option>
  </mat-select>
</mat-form-field>

.ts

default = '';

selectOpened() {
    this.default = 'audi';
}

此代码将在打开Select Box时对焦奥迪选项。希望这对你有用。

【讨论】:

  • 谢谢,问题是,我不需要一个值,我只想要焦点,这样的东西很好 document.querySelectorAll('.bedigungOptGroup').forEach(item=>{ if(item.getAttribute("antragsId")===this.antragsBereichValueSelected.toString()) item.scrollIntoView(); });
  • 您不需要价值?你怎么能专注于没有价值的期权?甚至,在您提供的片段中,您正在使用价值。
【解决方案2】:

对于任何可能有同样问题的人,结合 Maruthi Eranki 的回答,这就是我想出的..

  selectOpened() {
  document.querySelectorAll('.bedigungOptGroup').forEach(item=>{
  if(item.getAttribute("antragsId") === 
  this.antragsBereichValueSelected.toString()) 
     item.scrollIntoView(true);
  });
}

【讨论】:

猜你喜欢
  • 2018-06-25
  • 2018-02-27
  • 2019-01-28
  • 1970-01-01
  • 2019-02-07
  • 2023-03-21
  • 2020-03-30
  • 1970-01-01
  • 2019-05-30
相关资源
最近更新 更多