Retrieve the href value from a string and then associate the modified data with the element in an Angular application

Within my innerHtml, I have a string that looks like this:

<div class="wrapper" [innerHTML]="data.testString">

The data inside data.testString is as follows,

data.testString="<p>some info, email <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9beffee8efdbeffee8efb5f8f4f6">[email protected]</a>"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b0f1e080f3b0f1e080f55181416">[email protected]</a></a>  info </p>";

I need to include an aria-label for the anchor tag.

<a aria-label="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2a5e4f595e6a5e4f595e04494547">[email protected]</a>" href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c8bcadbbbc88bcadbbbce6aba7a5">[email protected]</a>"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ff8b9a8c8bbf8b9a8c8bd19c9092">[email protected]</a></a>

This is the code snippet added in the .ts file

ngAfterViewInit(): void {

    var myData = this.data.testString;
    var element = myData!.match!(/href="([^"]*)/)![1];
    
   
    var ariaLabel = "EmailId " + element;
    
    this.data.testString=
    this.data.testString!.replace('<a', '<a aria-label = "' + ariaLabel + '" ');
      
  }
}

However, I encountered the following error

global-error-handler.ts:26 TypeError: Cannot assign to read only property 'testString' of object '[object Object]'

What steps should be taken to resolve this issue?

Answer №1

I may not fully comprehend everything, but the following information might assist you:

  1. Dealing with string character escaping

var testString="<p>some info, email <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="631706101723170610174d000c0e">[email protected]</a>"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b4f5e484f7b4f5e484f15585456">[email protected]</a></a>  info </p>";

The problem lies in the quotation issue: a double-quoted string cannot contain double quotes without being escaped by the \ character (refer to https://www.w3schools.com/js/js_strings.asp -> Escape Character section)

You can address this problem by substituting some double quotes with single quotes:

"<p>some info, email <a href='mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9ddccdadde9ddccdadd87cac6c4">[email protected]</a>'><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9eeafbedeadeeafbedeab0fdf1f3">[email protected]</a></a>  info </p>"

  1. Working with regular expressions

var href = datar!.match!(/href="([^"]*)/)![1];

This might not be the exact pattern you require. You could try using:

var href = datar!.match!(/href=\'mailto:([a-z@.]+)'/)![1];

  1. Manipulating DOM elements

If you want to add the aria-label attribute to the , it is advisable to utilize Angular's

nativeElement.setAttribute(key, value)
or native javascript's querySelector methods (refer to https://indepth.dev/posts/1336/how-to-do-dom-manipulation-properly-in-angular and https://angular.io/guide/property-binding)

Lastly, I strongly recommend using RegExr for testing your regular expressions () and jsfiddle.net for testing your JavaScript code in a secure environment (https://jsfiddle.net/nkarfgx3/)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Element UI, featuring a wide array of components, contributing to bloated bundle sizes

I was looking into the following link. After following the instructions, I realized I am using class based components. Therefore, I am importing as shown below: import {Checkbox} from 'element-ui'; @Component({ components: { Checkbox } }) e ...

There are no shared properties with the type 'Properties<string | number, string & {}>'

Here's a look at my component: const linksContainerRef = useRef<HTMLDivElement>(null); const linksRef = useRef<HTMLUListElement>(null); const toggleLinks = () => { setShowLinks(!showLinks); }; interface LinkStyles ...

Issues arise when utilizing res.cookie, however, there are no troubles when using res.json

Using res.json() in my Express POST route response works fine. However, when I switch to using res.cookie(), I run into a strange issue of receiving a MongoDB 11000 Dup Key Error. The behavior that follows is somewhat puzzling: The Document is successfull ...

Circular function reference in Typescript occurs when a function calls itself

The functionality of this code snippet is rather straightforward; it either returns a function or a string based on an inner function parameter. function strBuilder(str: string) { return function next(str2?: string) { if(typeof str2 === "string& ...

Issues arise after upgrading Node and npm, causing an inability to execute any npm command

Following an upgrade to the latest Node and npm version, I encounter an error when attempting any npm command: C:\Users\...>npm doctor TypeError: Cannot read property 'prefix' of undefined at parseField (C:\Users&bs ...

Exploring Angular 2 Application Testing: Tips for Interacting with HTML Elements

In my Angular 2 Frontend testing journey, I came across a blog post ( ) where the author utilized ng-test TestBed for core testing in Angular. While the example provided was helpful for basic understanding, it lacked details on how to manipulate Elements. ...

Initiating a GET request to retrieve the file generated by the server

I am currently delving into the Mean stack and have encountered a challenge with downloading a file from my server-side application using the Angular front end. Despite successfully generating the file on the back end, clicking the download button on the f ...

Failure to Apply Angular Conditional Class

What is the reason for test-abc not being included? <div class="abc" [class.test-abc]="true"></div> I successfully implemented it with this syntax: [ngClass]="{'foo': true, 'abc': true}" ...

React and TypeScript threw an error: trying to execute setSearchQuery, which is not a function

I encountered an issue where I am receiving the error message: Uncaught TypeError: setSearchQuery is not a function in my Next.js / Typescript app. This error occurs while typing a search query into the search box. I have implemented a generic search funct ...

Achieving automatic checkbox selection in Angular 6 through passing a value from one component to another

My page named second.html contains the following code: <div class="col-lg-4 col-md-4 col-sm-4"> <input type="checkbox" class="checkmark" name="nond" [checked]="r=='true'" (change)="nond($event, check)"> ...

Encountering a problem where the alert popup does not appear when refreshing Chrome for the first time on the homepage in an Angular application

Firstly, I want to express my gratitude for your response to my previous inquiry. I am currently encountering an issue. When landing on the homepage for the first time, the alert popup does not work. However, once inside the application, it functions prop ...

Combine two elements in an array

I am faced with a challenge in binding values from an Array. My goal is to display two values in a row, then the next two values in the following row, and so on. Unfortunately, I have been unable to achieve this using *ngFor. Any assistance would be greatl ...

Prisma - Modify a single resource with additional criteria

Is it feasible to update a resource under multiple conditions? Consider the tables below: +----------+----------+ | Table1 | Table2 | +----------+----------+ | id | id | | param1T1 | param1T2 | | param2T1 | param2T2 | | idTable2 | ...

What could be causing the errors I'm encountering in my TypeScript component within AngularJS?

I am working with an AngularJS component written in TypeScript called news.component.ts. This component makes a call to a service named google.service.ts in order to fetch news RSS using a service that converts XML to JSON. Within the NewsComponent, I hav ...

Challenges with utilizing Ionic Native in a cross-platform application

I am currently developing an application using Ionic 2 that can function both as a website in a browser and as a mobile app on iOS and Android. One key aspect of the app is its use of the SQLite plugin when accessed on mobile devices. However, I have encou ...

Dealing with the "this" problem in TypeScript and its impact on scope

Here is my code snippet: class MyClass { name = "MyClass"; // traditional method definition getName1(){ return this.name; } // method defined as an arrow function getName2 = () => { return this.name; ...

The issue of the mat-select change event failing to trigger in an Angular 13 reactive form when using the

How to use mat-select within a form-group <mat-form-field appearance="outline"> <mat-select formControlName="formula" id="formula"> <mat-option [value]="metricFormula.TotalCount">{{l(&apos ...

Guide on making a Mapped Type in TypeScript using dynamic generic parameters

I am working with an object that contains one or more PreparedStatement. I am looking to create a general type definition for this object. Is there a way to achieve this in code? type PreparedRequest<Input, Result> = { input: Input; result: Resul ...

Adding images in real-time

I am currently working on an Angular application where I need to assign unique images to each button. Here is the HTML code snippet: <div *ngFor="let item of myItems"> <button class="custom-button"><img src="../../assets/img/flower.png ...

Encountered issue: The type 'Teacher[]' cannot be assigned to the type 'Teacher'

I am currently working on enhancing my angular application by adding a new service. However, I have encountered an error that I need help fixing: The error message states: Type 'Teacher[]' is not assignable to type 'Teacher'. Property ...