在Angular 5

时间:2017-12-09 13:46:00

标签: angular angular5

我有两张桌子。

我想将一个表的列宽设置为等于另一个表的列的宽度。

像这样:

    <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>

另一张桌子:

          <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>

我想要做的是让第一个表的所有标题始终等于第二个表的标题宽度。 因为在第二个表格中,它们会根据内容进行调整。

所以我知道我可以添加一个HostListener(&#39;窗口:调整大小&#39;) 但是我如何在Angular中分配这些值? 这样他们总是一样的。好像它是彼此的副本。 有什么指导吗?

2 个答案:

答案 0 :(得分:6)

首先,您需要获取源表列和目标表列的引用,您可以使用模板变量和@ViewChildren装饰器来完成此操作。

在你的模板中:

<!-- 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>

然后在你的组件类

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

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

  // ...
}

通过这种方式,您可以获得QueryList个元素引用,这样您就可以访问每个表标题的nativeElement(实际的DOM节点)并获取每个{{1}个}。注意offsetWidth@ViewChild装饰属性仅在@ViewChildren生命周期挂钩后可用。 AfterViewInit是一个类似于数组的数据结构,它有一些数组方法,如QueryListforEach等......

map内部,您希望迭代源表标题单元格列表,获取每个宽度,然后迭代目标标题单元格列表并设置宽度。为此,您可以使用ngAfterViewInit中的setStyle方法。然后,您也可以在Renderer2事件或其他任何

上调用此方法
window.resize

答案 1 :(得分:0)

这确实有效,但是如果您要按ctrl f5键,则会破坏表格。为了解决此问题,我不得不使用ngAfterVeiwChecked,但是当dom更改或屏幕尺寸更改等时,生命周期挂钩会不断触发...我不确定我是否能找到一种有效的方法。

在图片中,如果您要执行ctrl + f5键,则会看到标题断开,但是在此之后,如果只是通过“刷新”按钮刷新页面,就可以了。只是当您执行ctrl f5

Broken Headers