Home > Software engineering >  Check for URL's in array and iterate based on conditions in angular
Check for URL's in array and iterate based on conditions in angular

Time:10-23

I'm working with an angular project, I'm getting 3 types of links as shown below in the response of API and I'm iterating it in the html over an array.

case 1: <a class="test" href="https://www.google.com/" target="_blank">click here</a> ,
case 2: 'with only href ------- href="https://www.facebook.com/". ',
case 3: 'Without a tag and href ----- "https://www.google.com/"',

I want to show the href I'm getting in response as an hyperlink in my output and it should navigate to the appropriate link. For that I used [innerHTML]="result" and it working good for case 1.

As of now it is showing in output as a plain text for case 2 and case 3. I used regular expressions to convert them to links. It is working fine if I take them in separate variables.

How to use the conditions of regular expressions which I have already done while iterating over an array.

Please help me achieve this functionality.

I have updated my code in the stackblitz.

Working stackblitz is:

https://stackblitz.com/edit/angular-ivy-ckabj3?file=src/app/app.component.html

Response from API: There can be any number of objects with any conditions , not just below 3 only.

  apiresponse: any = {
    response: [
      {
        hrefmessages:
          'with only href ------- href="https://www.facebook.com/". ',
      },

      {
        hrefmessages: 'Without a tag and href ----- "https://www.google.com/"',
      },
      {
        hrefmessages:
          'with both a tag and href ------- <a  href="https://www.google.com/" target="_blank">click here</a>. ',
      },
    ],
  };

HTML:

<div *ngFor="let result of hrefArray">
  <p
    [innerHTML]="result"
  ></p>
</div>

TS:

  withHrefAndWithoutAtag() {
    let match = this.withJustHref.match(
      /(\b(https?|ftp|file):\/\/[-A-Z0-9 &@#\/%?=~_|!:,.;]*[-A-Z0-9 &@#\/%=~_|])/gi
    );
    console.log('match', match);
    let final = this.withJustHref.replace('href=', '');
    console.log('final', final);
    match.map((url) => {
      final = final.replace(
        url,
        '<a href="'   url   '" target="_BLANK">'   url   '</a>'
      );
    });
    console.log(final);
    this.withJustHref = final;

    return final;
  }

CodePudding user response:

The major change was to make your methods take a string as an input, instead of reading from global variables.

This is the result. Basically I check first the category, then call the right map method you already wrote.

app.component.ts

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

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

  apiresponse: any = {
    response: [
      {
        hrefmessages:
          'with only href ------- href="https://www.facebook.com/". ',
      },

      {
        hrefmessages: 'Without a tag and href ----- "https://www.google.com/"',
      },
      {
        hrefmessages:
          'with both a tag and href ------- <a  href="https://www.google.com/" target="_blank">click here</a>. ',
      },
    ],
  };

  ngOnInit(): void {
    this.hrefArray = this.mapHrefs();
  }

  mapHrefs(): string[] {
    return this.apiresponse.response.map((item) => {
      let message = item.hrefmessages;
      if (message.includes('<a ')) return message;

      if (message.includes('href')) return this.withHrefAndWithoutAtag(message);

      return this.withoutHrefAndAtag(message);
    });
  }

  withHrefAndWithoutAtag(item: string): string {
    let match = item.match(
      /(\b(https?|ftp|file):\/\/[-A-Z0-9 &@#\/%?=~_|!:,.;]*[-A-Z0-9 &@#\/%=~_|])/gi
    );
    console.log('match', match);
    let final = item.replace('href=', '');
    console.log('final', final);
    match.map((url) => {
      final = final.replace(
        url,
        '<a href="'   url   '" target="_BLANK">'   url   '</a>'
      );
    });
    console.log(final);

    return final;
  }

  withoutHrefAndAtag(item: string): string {
    let match = item.match(
      /(\b(https?|ftp|file):\/\/[-A-Z0-9 &@#\/%?=~_|!:,.;]*[-A-Z0-9 &@#\/%=~_|])/gi
    );
    let final = item;
    match.map((url) => {
      final = final.replace(
        url,
        '<a href="'   url   '" target="_BLANK">'   url   '</a>'
      );
    });

    return final;
  }
}

app.component.html

<div  *ngFor="let result of hrefArray">
  <p [innerHTML]="result"></p>
</div>
  • Related