如何设置动态的列宽HTMLtable
How to set the width of a column of a dynamic HTML table
我有如下代码
<table >
<thead >
<th *ngFor="let col of workData.columns;trackBy: trackByColumn;
let hindex=index;" [ngClass]="setWidth(col)" [index]="hindex">
</th>
</thead>
</table>
//TS File
setWidth(col){
if(col.field === 'First Name') {
col.width = '100px';
}
}
在上面的 table 中,我从 Http 调用中获取了列名列表和列数据,并根据它呈现 table。
如何根据名称动态设置每列的宽度。
例如:
Column: First Name Width:100px
Column: Last Name Width:90px
Column: Address Width: 150px
我正在使用 Angular 6
。我尝试了 javascript 解决方案以及 angular 中的 ngClass
和 ngStyle
。但是我无法掌握如何为每列设置宽度。
[ngClass]
需要一个对象。您正在调用一个 returns 没有
的方法
一种可能的方法是绑定 style
属性.
component.ts
public styles=
{
'First Name' : '100px',
'Last Name' : '90px',
'Address' : '150px'
};
component.html
<table >
<thead >
<th [style.width]="styles[col.field]"
*ngFor="let col of workData.columns; let hindex=index;" >
{{col.field}}
</th>
</thead>
</table>
您可以对 类 执行相同的操作(例如 class=classes[col.field]
)
您可以创建具有 'style' 属性的 JSON 对象,如下所示:
<code>workData = {
columns: [
{
field: "First Name",
style: {
width: "100px",
"background-color": "red",
color: "white"
}
},
{
field: "Last Name",
style: {
width: "200px",
"background-color": "blue",
color: "white"
}
},
{
field: "Address",
style: {
width: "300px",
"background-color": "yellow",
color: "black"
}
}
]};
然后在你的 file.html
</p>
<pre><code><table>
<thead>
<th [ngStyle]="col.style" *ngFor="let col of workData.columns;">{{col.field}}</th>
</thead>
</table>
现在您可以在 table
上添加多个样式
我有如下代码
<table >
<thead >
<th *ngFor="let col of workData.columns;trackBy: trackByColumn;
let hindex=index;" [ngClass]="setWidth(col)" [index]="hindex">
</th>
</thead>
</table>
//TS File
setWidth(col){
if(col.field === 'First Name') {
col.width = '100px';
}
}
在上面的 table 中,我从 Http 调用中获取了列名列表和列数据,并根据它呈现 table。 如何根据名称动态设置每列的宽度。
例如:
Column: First Name Width:100px
Column: Last Name Width:90px
Column: Address Width: 150px
我正在使用 Angular 6
。我尝试了 javascript 解决方案以及 angular 中的 ngClass
和 ngStyle
。但是我无法掌握如何为每列设置宽度。
[ngClass]
需要一个对象。您正在调用一个 returns 没有
一种可能的方法是绑定 style
属性.
component.ts
public styles=
{
'First Name' : '100px',
'Last Name' : '90px',
'Address' : '150px'
};
component.html
<table >
<thead >
<th [style.width]="styles[col.field]"
*ngFor="let col of workData.columns; let hindex=index;" >
{{col.field}}
</th>
</thead>
</table>
您可以对 类 执行相同的操作(例如 class=classes[col.field]
)
您可以创建具有 'style' 属性的 JSON 对象,如下所示:
<code>workData = {
columns: [
{
field: "First Name",
style: {
width: "100px",
"background-color": "red",
color: "white"
}
},
{
field: "Last Name",
style: {
width: "200px",
"background-color": "blue",
color: "white"
}
},
{
field: "Address",
style: {
width: "300px",
"background-color": "yellow",
color: "black"
}
}
]};
然后在你的 file.html
</p>
<pre><code><table>
<thead>
<th [ngStyle]="col.style" *ngFor="let col of workData.columns;">{{col.field}}</th>
</thead>
</table>
现在您可以在 table
上添加多个样式