Sta*_*low 5 angular-material angular
如何动态地将空添加到我的应用程序中mat-option不需要的所有内容mat-select。
喜欢 :
<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>
Run Code Online (Sandbox Code Playgroud)
任何想法?
小智 2
我使用了 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);
}
}
Run Code Online (Sandbox Code Playgroud)
而且,它对我有用!
| 归档时间: |
|
| 查看次数: |
15708 次 |
| 最近记录: |