angular 在我的应用程序中向所有不需要的 mat-select 添加空 mat-option [英] angular add empty mat-option to all not required mat-select in my app

查看:17
本文介绍了angular 在我的应用程序中向所有不需要的 mat-select 添加空 mat-option的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将动态空的 mat-option 添加到我的应用中所有不需要的 mat-select.

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);


  }
}

而且,它对我有用!

这篇关于angular 在我的应用程序中向所有不需要的 mat-select 添加空 mat-option的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆