我有两张桌子.
我想将一个表的列的宽度设置为等于另一个表的列的宽度.
像这样 :
<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>
Run Code Online (Sandbox Code Playgroud)
另一张桌子:
<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>
Run Code Online (Sandbox Code Playgroud)
我想要做的是让第一个表的所有标题始终等于第二个表的标题宽度.因为在第二个表格上,他们会根据内容调整大小.
所以我知道我可以添加一个HostListener('window:resize')但是如何在Angular中分配这些值呢?所以他们总是一样的.好像它是彼此的重复.任何指导?
首先,您需要获取源表列和目标表列的引用,您可以使用模板变量和@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>
Run Code Online (Sandbox Code Playgroud)
然后在你的组件类里面
@Component({ ... })
export class MyClass {
@ViewChildren('sourceTh')
sourceTh: QueryList<ElementRef>;
@ViewChildren('targetTh')
targetTh: QueryList<ElementRef>;
// ...
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以获得QueryList元素引用,因此您可以访问nativeElement每个表标题(实际DOM节点)并获取每个人offsetWidth.通知@ViewChild和@ViewChildren修饰属性仅在AfterViewInit生命周期挂钩后可用.阿QueryList是类似阵列的数据结构,并且它有一些阵列方法等forEach,map等...
在内部,ngAfterViewInit您希望迭代源表标题单元格列表,获取每个宽度,然后迭代目标标题单元格列表并设置宽度.为此,您可以使用setStyle方法Renderer2.然后你也可以在window.resize事件或其他方面调用此方法
@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`
);
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7299 次 |
| 最近记录: |