Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
Verifique las URL en la matriz e itere según las condiciones en angular

Estoy trabajando con un proyecto angular, obtengo 3 tipos de enlaces como se muestra a continuación en la respuesta de API y lo estoy iterando en el html sobre una matriz.

 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/"',

Quiero mostrar el href que recibo como respuesta como un hipervínculo en mi salida y debería navegar al enlace apropiado. Para eso usé [innerHTML]="result" y funcionó bien para el caso 1.

A partir de ahora, se muestra en la salida como texto sin formato para el caso 2 y el caso 3. Usé expresiones regulares para convertirlas en enlaces. Está funcionando bien si los tomo en variables separadas.

Cómo usar las condiciones de las expresiones regulares que ya he hecho al iterar sobre una matriz.

Por favor, ayúdame a lograr esta funcionalidad.

He actualizado mi código en el stackblitz .

Stackblitz de trabajo es:

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

Respuesta de la API: puede haber cualquier cantidad de objetos con cualquier condición, no solo por debajo de 3.

 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 class="test" 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; }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

El cambio principal fue hacer que sus métodos tomen una cadena como entrada, en lugar de leer variables globales.

Este es el resultado. Básicamente, verifico primero la categoría, luego llamo al método de mapa correcto que ya escribiste.

aplicación.componente.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 class="test" 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; } }

aplicación.componente.html

 <div *ngFor="let result of hrefArray"> <p [innerHTML]="result"></p> </div>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda