Function call inside ngStyle gets sanitized

1k Views Asked by At

I have a problem with style sanitization with Angular 8. I've used ngStyle multiple times, but this time i cannot set the border of a td element.

I am trying to set the border style based on a field. If this field has a relevant content for me then i hilghlight it, otherwise i don't. I don't know the number of possible values of the field, neither the exact values: it's complitely dynamic, I only know my values of interest.

I'm returning the border style from a function inside the .ts file. Here are the code snippets:

<ng-container matColumnDef="{{cam}}">
   <th mat-header-cell *matHeaderCellDef class="header"> {{cam}} </th>
   <td mat-cell *matCellDef="let piano" class="cellaMagazzino" [ngStyle]=" {'border':shouldHighlight(piano[cam])}">
      <div>
           <!--content-->
      </div>
   </td>
</ng-container>

My typescript function looks like this:

shouldHighlight(element){
if (this.listaCommittenti == undefined && this.listaNumOrdine == undefined) {
  let found = this.releventContentList.find(item => item.property == element.property)
  let result = found != undefined ? '3px solid ' + this.myVariable["color"] : ""
  return result
}

I used ngStyle calling functions other times, but in this case i get the error:

WARNING: sanitizing unsafe style value 3px solid rgb(241, 196, 15) (see http://g.co/ng/security#xss).

Is there some kind of configuration to do? is there a workaround?

2

There are 2 best solutions below

0
On BEST ANSWER

Does this work for you?

Typescript:

getHighlightColor():string {
   return  "rgba(255,255,255,1)"; 
}
shouldHighlight(): boolean {
    return true;
}

HTML:

<td mat-cell [style.border-color]="getHighlightColor(piano[cam])" [ngClass]="{ 'highlighted': shouldHighlight(piano[cam])}"

CSS:

.highlighted{
   border-width:3px;
   border-style:solid;
   border-color:transparent;
}
1
On

In general, I would strongly advice against using function calls in your template as it's a real performance killer. It's much better to calculate the desired classes and add them to your data instead.

Federico's approach is a nice work around, however you could also use your orignal approach and bypass the style security via bypassSecurityTrustStyle(yourStyleString) see Trusting safe values