【问题标题】:Dynamically change class of drop down items in angular 5以 5 角动态更改下拉项目的类别
【发布时间】:2018-06-07 17:14:31
【问题描述】:

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

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

这是我的对象数组,它使用角度材料垫选择产生下拉。

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"},
]

这是我使用 mat select 显示下拉菜单的 html 模板代码

<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 中,我添加了类

.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
                }
             }
            }

如果有人选择了第一个元素,那么最后两个元素的颜色将会改变。

此代码无法正常工作,请帮助

或任何更好的方法来实现这一点

【问题讨论】:

    标签: javascript angular typescript angular5 angular-material-5


    【解决方案1】:

    您的选择更改功能是 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() ?

    【讨论】:

    • 这是错字,我已经更新了问题,请咨询,课程正在申请所有元素。
    • 我也更新了索引变量,仍然面临同样的问题。有更好的方法来做到这一点。
    • 什么是 nproj ?
    • nproj 包含 emp 的数据
    • 你能重新检查一下整个逻辑吗,我发现了一些混乱
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多