Reputation: 7903
I have an Angular2 component (PropertyComponent) which is used with an attribute selector for each row of a bootstrap table:
<tbody>
<tr app-property *ngFor="let property of properties" [property]="property"></tr>
</tbody>
I would like to style the <tr>
row by adding a class based on the contents of the property object. Which I cannot do as it stands because I would like to put the style logic into the PropertyComponent. I could change the code to use the component selector:
<tbody>
<app-property *ngFor="let property of properties" [property]="property"></app-property>
</tbody>
and put the <tr>
tags into the component template, but this causes formatting issues due to the extra <app-property>
tags which wrapped around the table rows.
The PropertyComponent contains:
<td>{{property.key}}</td>
<td>{{property.value}}</td>
...
Is there a nice way to solve this problem?
Upvotes: 1
Views: 1512
Reputation: 34673
Base on the property
, you can use [ngClass] directive to apply the appropriate class. Here is the updated code:
<table>
<tbody *ngFor="let property of properties"
app-property [property]="property">
</tbody>
</table>
I have put the *ngFor
in <tbody>
, it will put each row in a <tbody>
tag. It may look as an ugly solution but it will serve the purpose for your case.
I don't know how your PropertyComponent
looks exactly, but I'll regenerate it with minimum required code:
@Component({
selector: '[app-property]',
template: `
<tr [ngClass]="getPropertyRowStyle()">
<td>{{property.key}}</td>
<td>{{property.value}}</td>
</tr>
`,
styles: [`
.class-one{ color:red; }
.class-two{ color:green; }
`]
})
export class PropertyComponent {
@Input() property: any;
getPropertyRowStyle(){
// implement your logic here to return the appropriate class.
// e.g.
if(this.property.key === 'one') {
return 'class-one';
}
else if(this.property.key === 'two') {
return 'class-two';
}
}
}
I am using the getPropertyRowStyle()
method to get the [ngClass]
according to the property
values. You can implement your own logic in that method. Also, I have put the <tr>
tag inside the component as you needed.
Here is a link to working PLUNKER DEMO
Upvotes: 2
Reputation: 4862
Sounds like you're looking for HostBinding
which allows you to bind properties in the parent element of your angular component.
@HostBinding('class.some-class') someClass = true;
Note that setting it to true will apply it.
Upvotes: 2
Reputation: 4838
If I've understood your question correctly, this is what you're looking for:
<tbody>
<tr *ngFor="let property of properties">
<app-property [property]="property"></app-property>
</tr>
</tbody>
This way you will have access to the property
on the <tr></tr>
tags. So you could do something like this
<tbody>
<tr *ngFor="let property of properties" [class.active]="property.name === 'potato">
<app-property [property]="property"></app-property>
</tr>
</tbody>
Upvotes: 0