DEV Community

John Peters
John Peters

Posted on

Angular Code Generation and injecting CSS

One aspect of code generation is injecting CSS at run time. Angular does this automatically by employing View Encapsulation which is just a fancy name for 'Use the component view's CSS first'.

But let's assume we are creating our components based on JSON only; which means we are bypassing the Angular component CSS system, like this:

     { 
       propertyName: "Log Errors", 
        type: "checkbox", 
        checked: false },
     { 
       propertyName: "Send Email on Failure",
        type: "checkbox",
        checked: false
     },
     { 
       propertyName: "Job 4 max duration",
        type: "duration",
        time: "01:02:10",
        style: { height: "6em" }
     },
Enter fullscreen mode Exit fullscreen mode

Our duration control looks like this when rendered:

Alt Text

It needs to have a height specified because the auto-generated HTML markup looks like this:

<div *ngIf="control.type === 'duration'">
   <div [ngStyle]="control.style">
      <input
         type="number"
         min="0"
         max="24"
         placeholder="HH"
         (change)="onHoursChanged()"
         value="{{ onGetHours(control.time) }}"
      />
      <input
         type="number"
         min="0"
         max="59"
         placeholder="MM"
         (change)="onMinutesChanged()"
         value="{{ onGetMinutes(control.time) }}"
      />
      <input
         type="number"
         min="0"
         max="59"
         placeholder="SS"
         (change)="onSecondsChanged()"
         value="{{ onGetSeconds(control.time) }}"
      />
   </div>
</div>
Enter fullscreen mode Exit fullscreen mode

If we don't have a height then the next control in the layout will override the view area of the duration control.

We use [ngStyle] to inject the height based on the control.style property, which is shown in the JSON above. It's simply an object which contains style markup like this:

style: { height: "6em" }

Enter fullscreen mode Exit fullscreen mode

It's not intuitive that it should work like that but this is how Angular's nGstyle works! The brackets [nGstyle] means to interpolate the string that follows, e.g use the value of control.style as control.style is NOT a literal string representation it's the name of a variable.

JWP2020

Top comments (0)