Using innerHTML in Angular to format strings


Posted by Steven

In preparation for the upcoming IT Hub Brunswick Barcamp, I updated the conference page with ideas for talks and speakers. To display the speakers, we are using the PrimeNG Carousel. This component displays content using slide effects. For this component to work, the content has to be defined in the controller, not the HTML template. This creates the following problem: Using string interpolation, strings defined in the controller can be displayed in the HTML template easily. However, they are displayed exactly how they are defined. Hence, formatting with HTML / CSS is not an option because the tags would not be interpreted at all.

The solution lies in the innerHTML directive:

  1. <div [innerHTML]=talk.text></div>

With this, the string in talk.text will be interpreted as HTML. Now, strings can be defined in the controller (or loaded from a database) like this:

  1. talksBestPractice: Talk[];
  2.  
  3. constructor() {
  4. this.talksBestPractice = [
  5. {
  6. portrait: 'speaker.jpg',
  7. speaker: 'Joe Speaker',
  8. text: 'My <strong>ultra cool talk</strong>.'
  9. }};
Category: 
Share: