本文介绍了角向我的应用程序中的所有不需要的垫选择添加空垫选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何向应用程序中所有不需要的 mat-select 动态添加空的 mat-option .

How can I add dynamically empty mat-option to all not required mat-select in my app.

喜欢:

 <mat-form-field appearance="outline">
         <mat-label>HMO</mat-label>
         <mat-select>
              <--how can I add this dynamically-->
              <mat-option>--</mat-option>
              <mat-option *ngFor="let hmo of HMOList"
                              [value]="hmo.Code">
                    {{ hmo.Desc }}
              </mat-option>
         </mat-select>
  </mat-form-field>

有什么主意吗?

推荐答案

我使用了Prince的响应,但是我的模型没有更新.我在OptionalMatSelectDirective

I used the response from Prince, but my model didn't update. And I added the following in OptionalMatSelectDirective

import { Directive, HostListener, OnInit, Renderer2, ElementRef, AfterViewInit } from '@angular/core';
import { MatSelect } from '@angular/material/select';

@Directive({
  selector: 'mat-select'
})
export class OptionalMatSelectDirective {

  constructor(private matSelect: MatSelect, private elementRef: ElementRef,
              private renderer: Renderer2) { }

  @HostListener('openedChange', ['$event'])
  onOpenedChange( isOpened : boolean)
  {

    if(!isOpened || this.matSelect.required)
    {
      return;
    }
    const matOption = this.renderer.createElement('mat-option');
    this.renderer.setAttribute(matOption, 'class', 'mat-option');
    this.renderer.listen(matOption,'click', ()=>
    {
      this.matSelect.value = '';
      **this.matSelect.ngControl.viewToModelUpdate(undefined);**
      this.matSelect.close();
    });

    const panel= document.querySelector('.mat-select-panel');
    if(!panel)
    {
      throw new Error('Cannot find mat select panel');
    }
    this.renderer.insertBefore(panel,matOption, panel.firstChild);


  }
}

而且,它对我有用!

这篇关于角向我的应用程序中的所有不需要的垫选择添加空垫选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 19:12