Search code examples
javascriptangulartypescriptangular5angular-material-5

Dynamically change class of drop down items in angular 5


If the first part of selected element (before "" character) match with first part of drop down element (before "" character), the class will not change the font color, if not match then class will fire and font color will change.

Logic needs to make dynamically enable disable element, if first part of name will not match with first part of selected element.

Here is my array of object which producing drop down using 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"},
]

Here is my html template code to display drop down using 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>

In my CSS, I added the class

.hiddenpro
{
    color: #ddd !important;
}

Here is my .ts file, I have implemented the 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
                }
             }
            }

If some one select the first element, the last two element color will be changed.

This code is not working properly, kindly help

Or any better way to achieve this


Solution

  • your select change function is hideEmp() and you are trying to trigger hideProjects() ?

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

    dont mix the index with other variables.

    where are you calling hideProjects() in the component.html ?