Tips for removing extra spaces when assigning a dynamic data-automation-id

I am currently developing a time selection widget in Angular to compare our current performance with previous data. This widget consists of two dropdown lists along with various buttons and input fields (for now, let's focus on the dropdown lists). I have a concern regarding the testing of these dropdowns. Below is an excerpt of my code:

timeselector.component.html

<select data-automation-id="timeselection-mode-primary">
  <option *ngFor="let mode of modes" [attr.data-automation-id]="'options_' + mode">
    {{ mode }}
  </option>
</select>

<!--additional input fields and toggle button-->

<select data-automation-id="timeselection-mode-secondary">
  <option *ngFor="let mode of modes" [attr.data-automation-id]="'previous_options_' + mode">
    Previous {{ mode }}
  </option>
</select>

Both dropdowns are fetching modes from the same array in my typescript file:

timeselector.component.ts

modes=['Calendar year', 'Year-to-date', 'Quarter', 'Monthly Pipe', 'Weekly Sprint']

The issue arises when dealing with options like Calendar year, Monthly Pipe, and Weekly Sprint due to the spaces in their names. Consequently, the data-automation-id becomes tricky to handle.

To address this, I included index values for each option as shown below:

<option *ngFor="let mode of modes; let i=index"
                [attr.data-automation-id]="'options_' +i">

and

<option *ngFor="let mode of modes; let i=index"
                [attr.data-automation-id]="'previous_options_' +i">

This solution resolves the issue, but my tech lead prefers not to use indexes. She suggests utilizing methods like truncate, trim, or similar, without relying on indices.

While familiar with techniques such as truncate, trim, and subString, I struggle to implement them at runtime within data-automation-id. Various attempts have been unsuccessful so far. Any assistance would be greatly appreciated.

Here is how the widget appears:

https://i.sstatic.net/4TbMg.png

Answer №1

To eliminate any white space within a string, one can utilize a function that involves using the split method (with white space) followed by the join method (with a dash - ). Here is an example:

  getModifiedText(mode){
    const splitMode = mode.split(' ');
    const joinMode = splitMode.join('-')
    return joinMode;
  }

To implement this in your files:

component.html:

<select data-automation-id="timeselection-mode-primary">
  <option *ngFor="let mode of modes;" [attr.data-automation-id]="'options_'+ getModifiedText(mode)">
      {{ mode }}
  </option>
</select>

component.ts:

  getModifiedText(mode){
    const splitMode = mode.split(' ');
    const joinMode = splitMode.join('-')
    return joinMode;
  }

In the provided code, splitMode.join('-') is used, but feel free to modify it based on your requirements. For instance, you could use splitMode.join('_').

For a functional demonstration, visit this Stackblitz link...

Answer №2

Have you thought about shifting the responsibility of creating the data-automation-id to the controller part (TS file) rather than keeping it in the template (HTML)?

For example, in the timeselector.component.ts, instead of defining modes like this:

modes=['Calendar year', 'Year-to-date', 'Quarter', 'Monthly Pipe', 'Weekly Sprint']

You could structure them like this:


modes = {
  name: 'Calendar year',
  id: 'options_calendar_year',
  ...
}

Then, in the timeselector.component.html you can use them as follows:

<select data-automation-id="timeselection-mode-primary">
  <option *ngFor="let mode of modes" [attr.data-automation-id]="mode.id">
    {{ mode.name }}
  </option>
</selection>

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

Attempting to fill a template using ngfor, wherein the initial 2 elements are displayed in a row

I am attempting to complete a task where, using an ngFor directive to iterate through an array, I need to display the first 2 elements in a row and the remaining elements in a descending column. It should look like this: first second third fourth fifth ...

What is the functionality of observable in Angular? The 'includes' property is not present in the 'Observable' type

I am currently diving into the world of Angular5 and I have been using Firebase to fetch data for my page display. While researching how to retrieve data from Firebase using AngularFire, I found that many examples were outdated. Eventually, I learned that ...

Cannon-js: Experience dynamic body bouncing on the y axis as it reacts to force applied on the x and z axes

Currently, I am working on an FPS game where the player controller applies force based on keyboard inputs to a dynamic cannon body. The angular dampening is set to 1 on the player body. The PlayerController class takes both the player class (which extends ...

Jest anticipated the mock function would have been invoked

Currently, I am running tests on a specific service. Here is the code snippet for the service: import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { ...

Encountered a Solana Error while handling Instruction 2: custom program error with code 0x1000078

While attempting to create an AMM Pool using the 'ammCreatePool.ts' script from the raydium-sdk repository, I encountered the following error message. I executed the script directly with ts-node src/ammCreatePool.ts and made modifications so that ...

Attempting to push my code changes to update my Angular website, however, encountering an error message in the console

Seeking help to resolve an error in my Angular app development using Visual Studio Code. Every time I try to publish updates, I encounter the following issue: __vite-browser-external:console:3 Uncaught Error: Module "console" has been externaliz ...

Sharing data between components in Angular 2 using the <router-outlet> technique

Having just started exploring Angular 2, I am eager to pass a boolean value from one component to another using <router-outlet> After some research, it seems like the best approach is to utilize a service. My aim is to toggle a boolean variable in ...

Encountered an issue while trying to install and run an Angular app: Error code TS2694 indicates that the Namespace does not have an exported member '

Attempting to construct and execute this angular project. Post building the project, with npm i I encountered some warnings, but no errors were found. After executing ng serve -o, the following errors appeared. Moreover, when accessed through the browser, ...

Troubleshooting in Angular: Router Provider causing Testing Failures

I have a Header Component that is called on the main component, as I have a *ngIf to check which route I am in and render the header differently. The code functions correctly and the header renders differently depending on where I am in the app. I am att ...

Combining different types in object keys helps prevent errors when working with TypeScript

Let's create a function type VarietyType = 'choice1' | 'choice2' const myFunction = (arg: Partial<Record<VarietyType, number>>) => { console.log(arg) } When calling it with an argument of the incorrect type myFunc ...

Guide to transitioning from Angular 4 to Angular 7: incorporating 'URLSearchParams' and 'RequestOptions'

I am in the process of updating my project from Angular 4 to Angular 7. I have successfully switched from using http to httpClient and changed to common/http as well. However, I am inexperienced with Angular and unsure how to convert urlSearchParams and ...

Encountered an issue finding element with Protractor - Error: script timed out after 20 seconds without receiving a response

I recently created a basic website using Angular 6 and I am facing some challenges while writing e2e tests for it. The first script is causing a lot of trouble for me as it throws the following error: C:\Users\user\Documents\workspace- ...

Issues arise when Typescript fails to convert an image URL into a base64 encoded string

My current challenge involves converting an image to base 64 format using its URL. This is the method I am currently using: convertToBase64(img) { var canvas = document.createElement("canvas"); canvas.width = img.width; canvas.height = img.he ...

Resolving a persistent AngularJS 1 constant problem with Typescript

I'm currently developing an application using TypeScript and AngularJS 1, and I've encountered a problem while trying to create a constant and passing it to another class. The constant in question is as follows: module app{ export class A ...

Guide on navigating to a specific page with ngx-bootstrap pagination

Is there a way to navigate to a specific page using ngx-bootstrap pagination by entering the page number into an input field? Check out this code snippet: ***Template:*** <div class="row"> <div class="col-xs-12 col-12"> ...

Obtaining Data from an Array with Reactive Forms in Angular 4

Just starting out with Angular 4 and trying to figure out how to populate input fields with information based on the selection made in a dropdown. <select formControlName="selectCar" class="form-field"> <option value="">Choose a car&l ...

Access to the 'currentUrlTree' property is restricted to the 'Router' class as it is marked as private and cannot be accessed externally

Currently, I am in the process of developing a login feature using jwt. However, I am encountering an error when attempting to retrieve the current URL of the active route as shown below. Error Message: [default] /Users/~/src/app/app.component.ts:51:75 P ...

How can we fetch data from the server in Vue 2.0 before the component is actually mounted?

Can anyone help me with this question noted in the title? How can I prevent a component from mounting in <router-view> until it receives data from the server, or how can I fetch the data before the component is mounted in <router-view>? Here a ...

Encountering an error message stating "Cannot access 'color' property of undefined" while setting up HighCharts in my xx.ts file

I am new to incorporating highcharts into my project and struggling with it. Despite following documentation and trying various methods, I have not been able to make it work as intended. My multi-series high charts were functioning properly until I decide ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...