Home > Mobile >  Change dynamic textbox border color in Angular
Change dynamic textbox border color in Angular

Time:03-08

I'm generating textboxes in angular

<span *ngFor="let list of lists[0].question; let i = index">
                    {{ list }}  
 <input type="text" *ngIf="i != lists[0].question.length-1" [(ngModel)]="values[i]"/>   
</span>

In this for loop textbox is being generated

i'm calling function on button click that get all the data from values variable

for (var i = 0; i < this.values.length; i  ) {

   if(this.values[i]=='somevalue')
    {
     // change this particular textbox color
    }

 }

I want to change the textbox border color of that particular index only not with all the textboxes values. Any Solution Thanks

CodePudding user response:

Well, if you want to change the color when you click a button you can use a variable (if only one of them can be change the color) or and array

Only one

indexAttention:number=-1;
checkValue(variable:string)
{
   //better than use a "typical for just use findIndex
   this.indexAttention=this.values.findIndex(x=>x==variable)
}

//and 
<input [style.border-color]="i==indexAttention?'red':null ...>

If you has more you can create an array with the index of the elements. For this we can use map

indexesAttention:number[]=[]
checkValue(variable:string)
{
   //map convert an array in another with the same elements and the values  calculates
   //in this case, if the value is equal to the variable
   //return the index, else return -1
   this.indexesAttention=this.values.map((x,index)=>x==variable?index:-1)
}

Then we write

<input [style.border-color]="indexesAttention.indexOf(i)>=0?'red':null ...>

NOTE: Is good know the differents methods to iterate in an array: find, findIndex,forEach,map... (Take a look to the mozilla page)

Update if we want to check severals words in a list it's better that our function return an array -not change the variable-

checkValue(variable:string):number[]
{
   return this.values
         .map((x,index)=>x==variable?index:-1)
         .filter(x=>x!=-1) //only want the index>>-1
}

So we can in click function

   click()
   {
         this.indexesAttention=[] //clean the array
         this.lists.forEach(x=>{   //iterate using forEach

                                   //concat two arrays
           this.indexesAttention=[...this.indexesAttention,
                                  ...this.checkValue(x)]
         })
   
   }

Now, we are using the spread operator to concat two arrays

NOTE: I know that there're many concepts but really, about arrays, there are no more

NOTE2: you can use also

<input 
[style.border-color]="lists.indexOf(values[i])>=0?'red':null"
...>

And you forget the functions

  • Related