5

I have two tables.

I want to set the width of the column of one table to equal the width of the column of another table.

Like this :

    <table class="table-header table">
        <thead class="table-bordered">
          <tr>
              <th>Name</th>
              <th>Last Name</th>
              <th>Gender</th>
              <th>Education</th>
            </tr>
        </thead>
      </table>

And the other table:

          <table class="table-header table">
         <thead class="table-bordered">
          <tr>
              <th>Name</th>
              <th>Last Name</th>
              <th>Gender</th>
              <th>Education</th>
            </tr>
        </thead>
      <tbody> 
         <tr> 
            <td> Ross </td>
             <td> Ross </td>
            <td> M</td>
            <td> BsC </td>
        ..
      </tbody>

What I want to do is have all the headers of the first table to always equal the headers width of the second table. Because on the second table they get resized based on the content.

So I know I can add a HostListener('window:resize') But how do I assign these values in Angular ? So that they're always the same. As if it's a duplicate of one another. Any guidance?

4
  • Why complicate and why not make them with a specific size for both tables and wrap the content or truncate with ellipses if it’s too big? This seems more of a css question than an angular one
    – Hugo Noro
    Dec 9, 2017 at 13:49
  • Because the width of the column should change based on the content. I dont know how long a text can be. And it should be displayed as it is :|
    – user9076499
    Dec 9, 2017 at 13:57
  • Fair enough but I still think this is more of a css question than an Angular one.
    – Hugo Noro
    Dec 9, 2017 at 14:02
  • Thanks, But it can't be done using only css. As in css I can only style, and not take width of one element and assign it to the other dynamically. Whenever one changes, the other one to change too.
    – user9076499
    Dec 9, 2017 at 14:06

2 Answers 2

9

First you need to get a reference of your source table columns and your target table columns, you can do this with a template variables and the @ViewChildren decorator.

In your template:

<!-- Source table -->
<table class="table-header table">
  <thead class="table-bordered">
    <tr>
        <th #sourceTh>Name</th>
        <th #sourceTh>Last Name</th>
        <th #sourceTh>Gender</th>
        <th #sourceTh>Education</th>
      </tr>
  </thead>
</table>

<!-- Target table -->
<table class="table-header table">
  <thead class="table-bordered">
    <tr>
      <th #targetTh>Name</th>
      <th #targetTh>Last Name</th>
      <th #targetTh>Gender</th>
      <th #targetTh>Education</th>
    </tr>
  </thead>
  <tbody>
    <!-- table body content -->
  </tbody>
</table>

And then inside you component class

@Component({ ... })  
export class MyClass {
  @ViewChildren('sourceTh')
  sourceTh: QueryList<ElementRef>;

  @ViewChildren('targetTh')
  targetTh: QueryList<ElementRef>;

  // ...
}

This way you can get a QueryList of elements references, so you can access the nativeElement of each table heading (the actual DOM Nodes) and get each individual offsetWidth. Notice @ViewChild and @ViewChildren decorated properties are only available after the AfterViewInit lifecycle hook. A QueryList is an array-like data structure and it has some array methods like forEach, map, etc...

Inside ngAfterViewInit you want to iterate over the list of source table header cells, get each one width and then iterate over target header cell list and set the width. For this, you can use the setStyle method from Renderer2. Then you can call this method also on window.resize event or whatever

@Component({ ... })  
export class MyClass implements AfterViewInit {
  @ViewChildren('sourceTh')
  sourceTh: QueryList<ElementRef>;

  @ViewChildren('targetTh')
  targetTh: QueryList<ElementRef>;

  constructor( private renderer: Renderer2 ) {}

  ngAfterViewInit() {
    this.resizeColumns();
  }

  resizeColumns() {
    let widths = this.sourceTh.map(th => th.nativeElement.offsetWidth);

    this.targetTh.forEach((th, index) => {
      this.renderer.setStyle(
        th.nativeElement, 
        'width', 
        `${widths[index]}px`
      );
    });
  }
}
6
  • Thank you so much! Life saver! But initially, the columns display different widths. only if I resize the window then they match once and then the smaller the window gets, the first table header gets smaller. the second doesn't change width. Why does that happen ? (I had to change the first table to be the target and the second the source. Because the second header gets its width based off the content . And the first header needs to have the same width as them even without a tbody)
    – user9076499
    Dec 9, 2017 at 23:36
  • the initial size of the columns may depend on the content of the table rows, if it's loaded dynamically it may not already be rendered, try putting a debugger inside ngAfterViewInit and see what is happening there... you might want to do the rendering on the next tick (using setTimeout) or calculate it once the content is already there, so yeah, it depends
    – Osman Cea
    Dec 10, 2017 at 0:20
  • Yea the data in the table is loaded on ngOnIniti() I call a service that gets the data. And use *ngFor to display it on the table. Can I add another HostListener that will listen to when the table is rendered? Because right now I call the function on window resize, so when I resize, it gets the width of the columns correctly. It's just initially that it doesn't and I have to resize for it to do. Maybe I should use another listener ?
    – user9076499
    Dec 10, 2017 at 0:27
  • You can't use @HostListener for custom events, @HostListener is just for DOM events on the host Node, it's like a wrapper for the native addEventListener API. Now, the main problem you have is how to do these calculations once the data is already loaded and after the view has been initialized, and this could be solved in many different ways, so I'd suggest opening another question. What I'd do is to call the service inside a route resolve, that way the data will already be there when component is loaded, therefore the table will be fine in AfterViewInit lifecycle hook.
    – Osman Cea
    Dec 10, 2017 at 9:22
  • Btw don't forget to upvote if the answer was helpful and accept it if it solved your initial problem.
    – Osman Cea
    Dec 10, 2017 at 9:22
0

This does work but if you were to do a ctrl f5 it breaks the table. In order for me to fixed this issue I had to use ngAfterVeiwChecked but however life cycle hook constantly triggers when the dom changes or screen size changes ect... I'm not sure I can find a efficient way.

In the picture you will see the headers break if you were to do a ctrl + f5 but however after that if you just simply refreshed your page via the refresh button it's fine. It's just when you do a ctrl f5

Broken Headers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy