Denver Dang
Denver Dang

Reputation: 2615

Javascript string with HTML

I have a component that looks something like this:

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  expandText: boolean = false;

  constructor() {}

  ngOnInit() {}

  stringShortener(text: string) {
    let str = text;

    if (this.expandText === false) {
      if (str.length > 80) {
        str =
          str.substring(0, 80 - 3) +
          '...' +
          ' ' +
          "<span style='color: red'>see more</span>";
      }
    } else {
      str = str + '...' + ' ' + "<span style='color: yellow'>see more</span>";
    }

    return str;
  }
}

On the HTML side it looks something like:

<div class="wrapper" (click)="expandText = !expandText">
<p>{{ stringShortener("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum") }}</p>
</div>

The issue is, that the HTML of myhtml is not rendered. I have tried with innerHTML, and that resulted in a span in some way. But if the span is something like: <span style="color: red">, or even if I use [ngStyle], [style.color], well, the style is not applied. So I only get a span with the text inside.

So how is this done with the proper rendering ?

EDIT: I have created a Stackblitz that shows the problem: https://stackblitz.com/edit/angular-ivy-xdi3z5?file=src/app/app.component.html

Upvotes: 0

Views: 85

Answers (2)

Yaroslav Skripalenko
Yaroslav Skripalenko

Reputation: 36

The issue is that you're passing your block with span tag as a text, so Angular just prints it as a normal text.

You can achieve desired functionality with *ngIf directive which will show needed span block, by adding a function which will tell you whether text is too long.

Upvotes: 1

Victor
Victor

Reputation: 109

Looks like you forgot the curly braces :)

    <div (click)="expandText= !expandText">
     <p>{{stringShorterner(myText)}}></p>
    </div>

Upvotes: 0

Related Questions