Home > Enterprise >  How to replace specific text to component in angular template?
How to replace specific text to component in angular template?

Time:07-31

I got the data from backend

{
success: "true"
message: "5000 $APPLES sold for 100 $GOLD"

}

So, I have angular component where I whant to show notify like this

<div > 
{{notify_message}}
</div>

// Displaying text: 5000 $APPLES sold for 100 $GOLD

But, I want replace $APPLES to <app-currency [type]="APPLES" [value]="5000 "></app-currency> and replace $GOLD to <app-currency [type]="GOLD" [value]="100"></app-currency>

So, how I can do that?

Wanted result:

<div > 
   <app-currency 
    [type]="APPLES" 
    [value]="5000">
   </app-currency> 
   sold for 
   <app-currency 
   [type]="GOLD" 
   [value]="100">
   </app-currency>

</div>

CodePudding user response:

You can use regex to find the relevant data. I made it generalize so it will search for the number and pick the number and the next word.

var r = /\d \s([$\w] )/g;
var searched = notify_message.match(r);
const allItems=[];
searched.map((val,index)=> {
   const prepareData = val.replace('$','').split(' ');
   allItems.push(prepareData);
});

console.log(allItems[0][0]); // 5000
console.log(allItems[0][1]); // APPLES
console.log(allItems[1][0]); // 100
console.log(allItems[1][1]); // GOLD

After this you can use it in the template.

CodePudding user response:

We first find notifications where we split the string into pieces. Where the first piece is a number and following piece starts with a $ we know we've found a notification. We then make an Notification out of it and push it to an array [] of notifications. In template we iterate over notifications and depending on type we can change things (e.g like the background) - but they use the same app-curreny component consuming data via @Input().

app.component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, OnDestroy {
  notificationsArr: Notification[] = [];

  ngOnInit() {
    // mock subscription
    of({
      success: 'true',
      message: '5000 $APPLES sold for 100 $GOLD',
    }).subscribe((response) => {
      if (response?.message) {
        const stringsArr = response.message.split(' ');

        for (let i = 0; i < stringsArr.length - 1; i  ) {
          // Check if string piece is Number and next pieace starts with $ then it's a Notification
          if (
            !Number.isNaN(Number(stringsArr[i])) &&
            stringsArr[i   1].charAt(0) === '$'
          ) {
            let notification: Notification = {
              value: Number(stringsArr[i]),
              type: stringsArr[i   1].replace('$', '').trim(),
            };
            console.log(notification);
            this.notificationsArr.push(notification);
          }
        }

        console.log(stringsArr);
      }
    });
  }

  ngOnDestroy() {}
}

export interface Notification {
  value: number;
  type: string;
}

Html:

<div  *ngIf="notificationsArr.length > 0">
  <ng-container *ngFor="let notification of notificationsArr">
    <app-currency [type]="notification.type" [value]="notification.value">
    </app-currency>
  </ng-container>
</div>

currency.component.ts

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

@Component({
  selector: 'app-currency',
  template: `<div [ngClass]="{'goldClass' : type === 'GOLD', 'appleClass' : type === 'APPLES'}">app-currency {{type}} {{value}}</div>`,
  styles: [`.goldClass { background-color : gold; } .appleClass { background-color : red; }`]
})
export class CurrenyComponent  {
  @Input() type: string;
  @Input() value: number;
}

Working example: https://stackblitz.com/edit/angular-ivy-kcyhxv?file=src/app/curreny.component.ts

  • Related