Search code examples
angulartypescripttruncation

Truncating text when it's in a typescript readonly template


I am trying to truncate text in a popup box, but the text for the popup box is not coming from an html file. The application is an angular application and the file that is building the popup box is an object within a module. Here is the code that is building the popup.

static readonly simpleTemplate = new PopupTemplate({
    title: '{name}',
    content: 
       '<b>Address:</b> {address}<br/>' +
       '<b>City:</b> {city}<br/>' +
       '<b>Other:</b> {other}'
    });

The "other" field is the field I need to truncate as we anticipate the text could be long. I have tried placing a slice pipe inside the curly brackets but that didn't work. I'm unsure of how to go about truncating this when there is no css file to go with this part of the module.


Solution

  • Our team built it and we want it truncated if it's longer than a specific length. Yes other is a local variable.

    Then you have two options:

    1. Update the PopupComponent your team built to add a custom class to the CSS of the PopupComponent.
    2. Truncate the value before passing it into the template.

    1. Custom Class:

    I don't know what the component is called. Let's call it PopupComponent. You and your team can update this component to include a custom class that has all the style you need.

    Then in the template, you just need to use the custom class.

    PopupComponent.component.css

    .truncate-text {
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;
    }
    

    example.component.ts

    static readonly simpleTemplate = new PopupTemplate({
        title: '{name}',
        content: 
           '<b>Address:</b> {address}<br/>' +
           '<b>City:</b> {city}<br/>' +
           '<b class="truncate-text">Other:</b> {other}'
        });
    

    2. Truncate the value before passing in:

    If you prefer not to update the existing component, you can manipulate the text before passing into the template.

    Below, you can shorten the string down and then append the three dots.

    example.component.ts

    
    const other = 'abcdefghijklmnopqrstuvwxyz'; // your local value.
    
    const maxLength = 3;
    const truncatedText = other.substring(0, maxLenght) + '...';
    
    static readonly simpleTemplate = new PopupTemplate({
        title: '{name}',
        content: 
           '<b>Address:</b> {address}<br/>' +
           '<b>City:</b> {city}<br/>' +
           '<b>Other:</b> {truncatedText}'
        });