27

I have a table in this form:

table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}

.blue {
    background-color: blue;
}

.green {
  background-color: green;
}

.red {
  background-color: red;
}
<table>
  <thead>
    <tr>
      <th class="blue">item 1</th>
      <th class="green" colspan="2">item 2</th>
      <th class="red" colspan="3">item 3</th>
    </tr> 
  </thead>
  <tbody>
    <tr>
      <td>data</td>
      <td>data</td>
      <td>data</td>
      <td>data</td>
      <td>data</td>
      <td>data</td>
    </tr>
    
  </tbody>
</table>

I would like to dynamically add colspan and colors to different th tag in angular 4: In my angular application I have:

.html file

<tr *ngFor="let item of items">
  <th>{{ item }}</th>
</tr>

.ts file

items: string[] = ['item 1', 'item 2', 'item 3']

how to add these different colspans and colors (look at the snippet what I want to achieve)? Thank you very much.

2 Answers 2

62

I think, This must work,

<tr *ngFor="let item of items">
  <th [attr.colspan]="item.colspan">{{ item.name }}</th>
</tr>

where Items are like,

items: any = [{colspan:1,name:'item 1'}, {colspan:3,name:'item 2'}.....]
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. This will definitely work. And what about the colors ? The same way ?
if it is a table attribute, same way
if its a style attr, then [style.background]="item.bgcolor"
I had to use: <th [attr.colspan]="item.colspan">{{ item.name }}</th> becasue Can't bind to 'colspan' since it isn't a known property of 'th'
0

You can still add color property to your item so that you can bind to it using [ngClass]="item.color"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.