What is preventing me from applying styles to the first word in my Angular ngFor iteration?

I'm currently attempting to customize the initial word of a string within my Angular ngFor loop. Strangely, the class gets applied but the style defined in my CSS file is not. Inline styling also does not seem to work - any ideas why?

This is the CSS I am trying to implement:

#page-image-title-table .first-entry-word {
  font-weight: 500;
}

Here is the function I am using to wrap the first word in an element with the aforementioned class:

formatTableEntry(tableEntry: string): string {
  const tableEntryParts = tableEntry.split(' ');
  const firstWord       = tableEntryParts[0];

  tableEntryParts.shift();

  const restOfString = tableEntryParts.join(' ');

  return `<span class="first-entry-word">${firstWord}</span> ${restOfString}`;
}

And this is the HTML code with my ngFor loop:

<div id="page-image-title-table">
  <div class="page-image-title-table-row" *ngFor="let tableEntry of tableEntries">
    <span [innerHTML]="formatTableEntry(tableEntry)"></span>
  </div>
</div>

You can view my demonstration here:

Answer №1

There appear to be several issues present.

  1. Tying a function to the directive

    [innerHTML]="formatTableEntry(tableEntry)"
    may result in performance issues with the default change detection strategy.

  2. The use of the innerHTML binding as attempted is not considered best practice in Angular.

  3. The default value for font-weight: 500, while bold is equivalent to 700.

  4. It seems that the Stackblitz is not functioning properly in Firefox and Chrome, although this may not directly relate to the main issue.

Potential Solution

You might consider creating a custom pipe to format the sentences as needed.

split.pipe.ts

@Pipe({
  name: 'split', 
  pure: true
})
export class SplitPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    if (!value) {
      return null;
    }

    return value.reduce((acc, curr) => {
      const [first, ...rest] = curr.split(" ");
      acc.push({ first: first, rest: rest.join(" ") });
      return acc;
    }, []);
  }
}

This custom pipe can then be used along with the *ngFor directive similar to how the keyvalue pipe works.

Feel free to give this approach a try.

app.component.ts

@Component({
  selector: "my-app",
  template: `
    <div id="page-image-title-table">
      <div 
        class="page-image-title-table-row" 
        *ngFor="let tableEntry of (tableEntries | split)"
      >
        <span>
          <span class="first-entry-word">{{ tableEntry.first }}</span>
          {{ tableEntry.rest }}
        </span>
      </div>
    </div>
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  tableEntries = [
    "First element of the array",
    "Second sample element of the array",
    "lorem ipsum dolor sit amet",
    "Quick brown fox jumps over the lazy dog"
  ];
}

app.component.css

#page-image-title-table .first-entry-word {
  font-weight: 700;
}

To see a live demonstration, you can visit the following link: Stackblitz

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

What is the correct way to markup the semantic form label assistance text?

When designing a form, there are certain form elements that may need explanatory text to clarify their function. One approach is to wrap this text in a paragraph element, as demonstrated below: label p { margin-top: -1px; font-size: smaller; } <div ...

Challenges with aligning Fontawesome stacks

I utilized the code example from Fontawesome's website to create a pair of stacked social media buttons and enclosed it in a div element to float them to the right side of the page. <div class="social-icons"> <span class="fa-stack fa-lg"> ...

Tap on the image placeholder to replace it with your own image

Just starting out, I have the following HTML code within a <form>: <div class="image-upload"> <img id="send_photo_img1" src="assets/images/index2.png"/> <input id="send_photo_input1" type="file"/> <img id="send_photo_img2" sr ...

Arrange gridster items horizontally in angular-gridster2 after reaching the mobile breakpoint

I have successfully integrated angular-gridster2 to organize multiple widgets on a page. The widgets are all aligned and functioning properly when viewed in a desktop browser. However, when the same page is accessed on a mobile device, the widgets stack ve ...

Handling the width and borders of CSS cells that are positioned outside of a table

Welcome! I recently created a simple gantt organizer as part of a demo. My goal was to make the main table scrollable while keeping certain columns "frozen" for easy visibility when navigating through the data. To achieve this, I followed some advice found ...

How can I align 2 images side by side at the top and 1 beside them at the

I'm attempting to recreate an image using Bootstrap to minimize the need for additional CSS. The image I'm trying to replicate can be viewed https://i.sstatic.net/gBaVo.png. I've been struggling with the code and haven't been able to ge ...

Retrieving the value of a checkbox when clicked in Angular 2

I am trying to use ngModel binding to check the status of a checkbox. After calling console.log(activeCheckbox);, I can see that the ngmodel and its value property are set to true in the console. However, when I immediately call console.log(activeCheck ...

The text that follows the cursor seems to stand out taller than the rest

When I type words in a textarea input field, the cursor seems to be taller than it should be (as shown below). What is causing this issue and is there a way to make it as tall as the words with a font size of 38px? Here is the code snippet: <textarea n ...

Load link dynamically using the rel attribute

I am trying to implement dynamic content loading using jQuery's .load() function. The links are stored in the .rel attribute of the anchor tags. My setup looks like this: <script> $(document).ready(function(){ $('.sidebar_link').clic ...

Using Selenium with C# to input text into an HTML <input> tag is not functioning properly

I need help figuring out how to fill in an input field on a website using HTML. Here is what the section of the website () looks like: <div class="flex-item-fluid"> <input autocomplete="username" autocapitalize="off" ...

Solving Issues with Names, Modules, and Other Strange Elements in Angular Universal

While the main app runs smoothly, attempting to serve the bundled SSR results in perplexing errors that I'm struggling to comprehend. All setup details are provided below for reference. The process of creating a server-side app seems riddled with sma ...

Using the `ngrx` library to perform an entity upsert operation with the

I am facing a certain challenge in my code. I have an action defined as follows: export const updateSuccess = createAction('Success', props<{ someId: string }>()); In the reducer, I have an adapter set up like this: export const adapter: ...

Get the QR code canvas image with a customized background by downloading it

I am having trouble with downloading a QR code canvas image with a background. The download works fine, but my device is unable to scan the code properly due to an incomplete border. I need to add a white background behind it to make it larger. Current im ...

Extract information from a JSON file and import it into an Angular TypeScript file

How can I retrieve data from a JSON file and use it in an Angular typescript file for displaying on web pages? this.http.get<any>('http://localhost:81/CO226/project/loginResult.json').subscribe((res: Response)=>{ }); Here ...

Implement a feature in JavaScript that highlights the current menu item

I'm currently developing a website at and have implemented a JavaScript feature to highlight the current menu item with an arrow. The issue I'm facing is that when users scroll through the page using the scrollbar instead of clicking on the men ...

Completing a submission on a bootstrap form, using innerHTML and displaying an alert

I am currently having an issue with navigating to the home page after submitting a form in Bootstrap. Although I have successfully implemented an alert message upon submission, the page does not redirect to the home page as expected. Instead, it redirects ...

Is there a way to pass locale data using props in VueJS Router?

To access hotel data, the URL path should be localhost:8080/hotel/:id (where id is equal to json.hoteID). For example, localhost:8080/hotel/101 This path should display the specific data for that hotel. In order to achieve this, we will utilize VueJS vu ...

Having trouble getting CSS to center text properly. It just won't cooperate

After spending 2 days trying to figure this out on my own, I have come to a dead end. It seems that my lack of expertise in CSS is the root cause of the issue. Here is the code snippet I am working with: <table class="demo"> <tr> <th style ...

The error message "TypeError: self.parent.parent.context.parseInt is not a function" indicates that

My goal is to set the height of an image using ngStyle by calculating it with a Math operation in the following way: <div [ngSwitch]="tbNm?tbNm:'itm0'"> <ion-list *ngFor="let vl of scrnshot;let ind=index"> <img *ngSwitch ...

What steps can I take to use CSS to disable a webpage?

Is there a way to create a disabled web page using CSS where users cannot click on any content and only view the content below the screen? ...