gpt4 book ai didi

angular 在我的应用程序中向所有不需要的 mat-select 添加空 mat-option

转载 作者:行者123 更新时间:2023-12-04 15:32:25 25 4
gpt4 key购买 nike

如何动态添加空 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>

任何的想法?

最佳答案

我使用了 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);


}
}
而且,它对我有用!

关于angular 在我的应用程序中向所有不需要的 mat-select 添加空 mat-option,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60949388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com