如何动态添加空mat-option
给所有不需要的mat-select
在我的应用程序中。
like :
<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中添加了以下内容
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);
}
}
而且,它对我有用!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)