Mastodon

Using InnerHTML in Angular to format Strings

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:

<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:

talksBestPractice: Talk[];
 
constructor() {
this.talksBestPractice = [
  {
	portrait: 'speaker.jpg',
	speaker: 'Joe Speaker',
	text: 'My <strong>ultra cool talk</strong>.'
  }};