Reputation: 8970
I have an angular app that is rendering a table of employee details. There is a datapoint called Optional
that determines if it should show up by default.
My goal here is to hide these rows by default and then be able to toggle them on/off with a click of a button.
Example:
<table class="table table-condensed table-striped" *ngIf="s.fields">
<tbody>
<tr *ngFor="let f of s.fields.field" [class.hidden]="f.Optional == 1">
<td>{{ f.FieldTitle }}</td>
<td>{{ f.Value }}</td>
</tr>
</tbody>
</table>
So far, I have it hiding the rows correctly that are optional by adding a class to them.
I ultimately need to be able to click a button to show/hide these hidden rows but I am unsure how to go about this approach.
Do I use CSS for this or somehow create a 2-way binding or model for it?
Upvotes: 2
Views: 20042
Reputation: 2290
Here is my solution for you, using ng-container and a function to determine the state based on optional and toggle state.
TS
state: boolean = false;
isAllowed = (optional) => {
return optional === 0 ? true : this.state;
}
changeState = () => {
this.state = !this.state;
}
HTML
<table class="table table-condensed table-striped" *ngIf="s.fields">
<tbody>
<tr *ngFor="let f of s.fields.field">
<ng-container *ngIf="isAllowed(f.Optional)">
<td>{{ f.FieldTitle }}</td>
<td>{{ f.Value }}</td>
</ng-container>
</tr>
</tbody>
</table>
<br>
<button (click)="changeState()">Show/Hide</button>
Upvotes: 7
Reputation: 1439
I assume your data look something like that:
s = {
fields: {
field: [
{
FieldTitle: 'field 1',
Value: ' value 1',
Optional: '1'
},
{
FieldTitle: 'field 2',
Value: ' value 2',
Optional: '0'
},
{
FieldTitle: 'field 3',
Value: ' value 3',
Optional: '1'
},
{
FieldTitle: 'field 4',
Value: ' value 4',
Optional: '0'
},
{
FieldTitle: 'field 5',
Value: ' value 5',
Optional: '0'
}
]
}
}
This can be achieved with simple conditions on table data and a simple click
listener:
<table class="table table-condensed table-striped" *ngIf="!isToggled && s.fields">
<tbody>
<tr *ngFor="let f of s.fields.field">
<td *ngIf="f.Optional == 1">{{ f.FieldTitle }}</td>
<td *ngIf="f.Optional == 1">{{ f.Value }}</td>
</tr>
</tbody>
</table>
<br>
<button (click)="onToggle()">toggle</button>
Make sure you have on your component.ts the isToggled
boolean set to false
and an onToggle
function.
Sample: stackblitz.com
Upvotes: 0