skip to Main Content

I’m faced with this issue that I never noticed before.

I have a custom component (<field-info></field-info>) whose HTML looks like

<span [ngStyle]="{ 'width' : cssWidth }" class="my-auto">
  <span>
    <span [innerHtml]="iconType" style="vertical-align: middle;" class="my-auto material-icons-outlined">
    </span>&nbsp;{{unitDisplay}}
  </span>
</span>

cssWidth is set to 75px in this case. The problem is that the content above gets compressed on a single column because the field-info HTML element is not 75 pixel wide.

enter image description here

If I open Chrome dev tools and manually add style: 75px; to the field-info HTML element, then the component’s content stretches correctly.

How do I tell my component to stretch to whatever width is needed to fit its own content exactly ?

Thanks.

2

Answers


  1. Chosen as BEST ANSWER

    I was able to modify the component's DOM this way:

    constructor(private elementRef: ElementRef) {
    
    }
    
    ngAfterViewInit(): void {
        const ne = this.elementRef.nativeElement as HTMLElement;
        ne.style.setProperty("width", this.cssWidth);
        ne.classList.add("my-auto");
    }
    

    Now the component's width is set properly (cssWidth is an input variable) and I can also add a boostrap class to it.


  2. You could try to use fit-content width option in your CSS!

    https://developer.mozilla.org/en-US/docs/Web/CSS/fit-content

    Alternatively, auto lets the browser calculate the width for your element as well.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search