Angular apply css dinamically without knowing the properties

38 Views Asked by At

i need to apply css to a field, but i don't know which elements the user want to change. I have a module where a user can create forms dinamically, creating fields and so on, and they can set styles too. They will write in the box all the stile they want, like : color: red; background-color: black...etc; I found many questions about but all the answers require everytime to know the property to change, so my question is : Is possible in angular to pass to a field a variable that contain { property: value;...} and apply it dinamically?

Example of text written by user:

{color:red; background-color: white; border: red 2px solid; opacity: 0.3; position: absolute; top: 0; left: 0; width: 100%;height: 100%;
}

Example of the input field where i need to apply it:


 <input matInput [type]="getInputType()"  [formControlName]="field.Name" [readonly]="field.Readonly"
        [required]="field.Required" [(ngModel)]="record[field.Name]" (ngModelChange)="onRecordValueChange()">

I've tryed [ngStyle]= variable but ngstyle seems requiring the property and then ou can bind a variable to it, but if i have to map all the possible variables in css it will be a wall of code... Hope someone can help me out with this tricky problem. Thanks in advance.

1

There are 1 best solutions below

1
Eliseo On

Update correct in the code

const keypar=b.replace(/['"]+/g, '').split(":")

To allow some like

  style="{'color':'red'}"

You can create an object based in the string and use ngStyle

  style="{color:red; background-color: white; border: red 2px solid; opacity: 0.3; position: absolute; top: 0;left: 0; width: 100%;height: 100%;  }"

  styleObj=(this.style.replace("{","").replace("}","")).split(";").reduce((a,b)=>{
   const keypar=b.replace(/['"]+/g, '').split(":")
   if (keypar.length>1)
       a[keypar[0].trim()]=keypar[1].trim();
   return a
  },{})


<div [ngStyle]="styleObj">Hello</div>

NOTE: I choose use split instead of use a complex Rexepr to conver the string to a json object and use JSON.parse

stackblitz