Building  Large-Scale Web Applications with Angular
上QQ阅读APP看书,第一时间看更新

Formatting exercise steps with innerHTML binding

One of the sore points in the current app is the formatting of the exercise steps. It's a bit difficult to read these steps.

The steps should either have a line break (<br>) or be formatted as an HTML list for easy readability. This seems to be a straightforward task, and we can just go ahead and change the data that is bound to the step interpolation, or write a pipe that can add some HTML formatting using the line delimiting convention (.). For a quick verification, let's update the first exercise steps in workout-runner.component.ts by adding a break (<br>) after each line:

`Assume an erect position, with feet together and arms at your side. <br> 
 Slightly bend your knees, and propel yourself a few inches into the air. <br> 
 While in air, bring your legs out to the side about shoulder width or slightly wider. <br> 
 ... 

As the workout restarts, look at the first exercise steps. The output does not match our expectations, as shown here:

The break tags were literally rendered in the browser. Angular did not render the interpolation as HTML; instead, it escaped the HTML characters, and we know why, security!

How to fix it? Easy! Replace the interpolation with the property binding to bind step data to the element's innerHTML property (in exercise-description.html), and you are done!

<div class="card-text" [innerHTML]="steps"> 

Refresh the workout page to confirm.

Preventing Cross-Site Scripting Security (XSS) issues
By using innerHTML, we instruct Angular to not escape HTML, but Angular still sanitizes the input HTML as described in the security section earlier. It removes things such as  <script> tags and other JavaScript to safeguard against XSS attacks. If you want to dynamically inject styles/scripts into HTML, use the DomSanitizer to bypass this sanitization check.

Time for another enhancement! It's time to learn about Angular pipes.