1

I have a component that show/hide element by clicking a button.

This is my html

  <div *ngFor="let history of histories | sortdate: '-dateModified'">
    <p><b>{{ history.remarks }}</b> - <i>{{history.dateModified | date:'short'}}</i></p>
    <a href="google.com" 
    [class.datatable-icon-right]="history.$$expanded" 
    [class.datatable-icon-down]="!history.$$expanded" 
    title="Expand/Collapse Row" 
    (click)="toggleExpandRow(history)"></a>
      <!-- hide/show this by clicking the button above.-->
    <div *ngFor="let step of history.steps; let i = index">
      <b>{{i+1}}.</b> {{step}}
      <span class="clear"></span>
    </div>
    <hr />
  </div>

and my .ts

  toggleExpandRow(row) {
    console.log('Toggled Expand Row!', row);
    //row
    return false;
  }

trying to search but, can't find any same sample.

On jquery, I can do this, but on Angular2, I am having hard time to figure this.

CozyAzure
  • 8,280
  • 7
  • 34
  • 52
Storm Spirit
  • 1,440
  • 4
  • 19
  • 42

2 Answers2

2

There are two options:

1- You can use the hidden directive to show or hide any element

<div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
  <strong>List Saved!</strong> Your changes has been saved.
</div>

2- You can use the ngIf control directive to add or remove the element. This is different of the hidden directive because it does not show / hide the element, but it add / remove from the DOM. You can loose unsaved data of the element. It can be the better choice for an edit component that is cancelled.

<div *ngIf="edited" class="alert alert-success box-msg" role="alert"> 
  <strong>List Saved!</strong> Your changes has been saved.
</div>
Feras Al Sous
  • 1,073
  • 1
  • 12
  • 23
1

Use the ngIf in your repeated rows. Create a boolean property called showStep to indicate whether the row should be expanded or not.

<div *ngFor="let step of history.steps; let i = index" ngIf="history.showStep">
  <b>{{i+1}}.</b> {{step}}
  <span class="clear"></span>
</div>

Then, in your .ts file:

  toggleExpandRow(history) {
     history.showStep = !history.showStep
     //note the same porperty of showStep that is used in your html
  }

Extra:

In fact, to save a few lines of codes, you don't even need the toggleExpandRow function at all. You can do it inline in your html:

//other attributes omitted for brevity
<a (click)="history.showStep = !history.showStep">
CozyAzure
  • 8,280
  • 7
  • 34
  • 52