Home > Software engineering >  I have {{data}} in angular thats coming from the backend. This {{data}} holds a sentence, how do i a
I have {{data}} in angular thats coming from the backend. This {{data}} holds a sentence, how do i a

Time:11-25

I have a code that looks like

<mat-panel-title>
    {{data}}
</mat-panel-title>

This data is a variable that holds a sentence like " My name is so&so".

I need to add css for "name" such that it is blue colour. but since {{data}} holds the whole sentence i do not know how to split it up. I use ts files for this project. im new to angular could you please help me out.

CodePudding user response:

try to create a directive :

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[highlight]'
})
export class HighlightDirective {

 
  constructor(el: ElementRef) {
    this.changeColor(el);
 }

 changeColor(el: ElementRef) {
  
   //call the  el.nativeElement.style.color  and put your logic.....
 
 }

}

then call it by the selector :

<h1 highlight>{{data}}</h1>

CodePudding user response:

write a function that returns the name as the last word and also the sentence without name:

getPartsOfSentence(data: string){
const x = text.split(" ");
 const name = x[x.length-1];
 const sentenceWithoutName = x.slice(0, -1).join(" ");
return ({name, sentenceWithoutName});
}

deconstruct two variables and use them separately in your html and style them:

const {name, sentenceWithoutName} = getPartsOfSentence(data);
  • Related