JCrew0
JCrew0

Reputation: 129

How do I bold a String that I'm passing in through a message service?

My service looks as follows:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class MessageService {
  messages: string[] = [];

  add(message: string) {
    this.messages.push(message);
  }

  clear() {
    this.messages = [];
  }
}

The HTML for the associated component looks like this:

<div>
    <h4>Status Messages:</h4>
    <div *ngFor='let message of messageService.messages'> {{message}} </div>
  </div>

I normally call it in other components like this:

this.messageService.add('Completed all current actions.')

Say I wanted to just bold the word "Completed". Any ideas on how to do that?

Upvotes: 0

Views: 1227

Answers (1)

John Malkoln
John Malkoln

Reputation: 461

You just need to changed your data model.

You can define Message, which represents single sentence with array of words, which need to be highlighted.

export interface Message {
    text: string;
    wordsToHighlight: string[];
}

Then during iteration over the messages array, create html string and use HTML element's innerHTML or outerHTML property to render it. Pay attention on getHighlightedText method below.

Your component may look like this:

@Component({
    selector: 'app-demo',
    template: `
        <div *ngFor="let message of messages" [outerHTML]="getHighlightedText(message)"></div>
    `
})
export class DemoComponent implements OnInit {

    messages: Message[];

    constructor(private readonly messageService: MessageService) {}

    ngOnInit(): void {
        this.messages = this.messageService.messages;
        this.messageService.add({ text: 'Completed all current actions', wordsToHighlight: ['all', 'actions'] })
    }

    getHighlightedText(message: Message): string {
        const words = message.text.split(' ');

        return words.map((word) => {
            const highlight = message.wordsToHighlight.some((wordToHighlight) => word.toLowerCase() === wordToHighlight.toLowerCase());

            if (highlight) {
                return `<b>${word}</b>`;
            } else {
                return word;
            }
        }).join(' ');
    }
}

Message service:

@Injectable({
    providedIn: 'root',
})
export class MessageService {
    messages: Message[] = [];

    add(message: Message) {
        this.messages.push(message);
    }

    clear() {
        this.messages = [];
    }
}

Upvotes: 1

Related Questions