在 angular 5 中动态更改 class 的下拉项目

Dynamically change class of drop down items in angular 5

如果 selected 元素的第一部分(“”字符之前)与下拉元素的第一部分(“”字符之前)匹配,则 class 不会改变字体颜色,如果不匹配则 class 会触发并且字体颜色会改变。

逻辑需要动态启用禁用元素,如果名称的第一部分与 selected 元素的第一部分不匹配。

这是我的对象数组,它使用 angular material mat select 生成下拉列表。

emp[
    {"id":1001,"name":"robin_010"},
    {"id":1002,"name":"robin_020"},
    {"id":1003,"name":"robin_030"},
    {"id":1004,"name":"sushil_040"},
    {"id":1005,"name":"sushil_050"},
]

这是我的 html 模板代码,使用 mat select

显示下拉列表
<mat-form-field>
<mat-select [(value)]="sel (change)="hideEmp()" [formControl]="toppings" 
multiple required>
<mat-option [class.hiddenpro]="is_hide" *ngFor="let p of emp;
 [value]="p" >{{p.name}}</mat-option>
</mat-select>
</mat-form-field>

在我的 CSS 中,我添加了 class

.hiddenpro
{
    color: #ddd !important;
}

这是我的 .ts 文件,我已经实现了 hideProjects()

        hideEmp()
            {

       /* sel is selected object, getting from  drop down, once selected,
 to get the name property from the object, looping through for each.
    */ 

                if(this.sel && this.sel.length){
                var proc="";
                this.sel.forEach(res=>{
                proc+=res.name + " ";   // proc containing the name
                })
                }

    // Get the first part of name property in var procd (before "_")

                var procd=proc.substring(0, proc.indexOf("_"));

    //Looping emp data to compare all the values through var procd

                for(let i=0; i<this.emp.length; i++){

    //hdata containing the first part of elements  (before "_")

                var hdata=this.emp[i].name.substring(0, this.nproj[i].name.indexOf("_"));

    //comparing selected element with drop down data

                if(procd==hdata)
                {
                this.is_hide =false;  // hiddenpro will not work
                }
                else
                {
                this.is_hide =true;  //hiddenpro will work
                }
             }
            }

如果有人 select 第一个元素,最后两个元素的颜色会改变。

此代码无法正常运行,请帮助

或实现此目标的任何更好方法

您的 select 更改函数是 hideEmp() 并且您正在尝试触发 hideProjects() ?

<mat-option [class.hiddenpro]="is_hide" *ngFor="let p of nproj;
 let i = index;" [value]="i" >{{p.name}}</mat-option>
</mat-select>

不要将索引与其他变量混合使用。

您在 component.html 中的何处调用 hideProjects()?