jack miao jack miao - 4 months ago 8
HTML Question

How to present 2 types of json on the same view each one at a time based on button click

I have a view with 2 buttons:

List 1
&
List 2


in my html I have an action when someone click on
List 1
im bringing the json for
List 1
and presenting it, and I have an action that when I click on
List 2
I get the json for
list 2
,

but I dont know how to present it cause its in a different struct then the list that comes back for
List 1
...
what would be the better solution to print 2 different structure of json but on the same view? so if
List 2
was click I want to delete
List 1
from the view and show
List 2
and vice versa.

this is my component.ts:

export class MyCmp implements OnInit {

list1Data: Observable<List1Bulk[]>;
list2Data: Observable<List2Bulk[]>

constructor(private _myService: MyService) {
};

public showList1(): void {
this.list1Data = this._myService.getList1Data();
}

public showList2(): void {
this.list2Data = this._myService.getList2Data();
}
}


and this is my component.html:

<div>
<!-- list 1 button -->
<button md-button
(click)="showList1Data()"
class="md-primary">List1</button>

<!-- list 2 button -->
<button md-button
(click)="showList2Data()"
class="md-primary">List2</button>

<md-content>
<h1 align="center">{{title}}</h1>
<h2>lists:</h2>
<div class="list-bg" *ngFor="#bulk of list1Data | async">
ID: {{bulk.id}} Number of Items: {{bulk.numberOfItems}}
</div>
</md-content>


How can I change my view so I can present also list2data? i want to click on List 2 button , clear List 1 data and present List 2 data..

thanks!

Answer

Use *ngIf or *ngSwitch for this. In your MyCmp declare 2 boolean properties showingList1 and showingList2. Update these properties accordingly when buttons are clicked. Then your template will be something like this:

<div>
<!-- list 1 button -->
<button md-button
        (click)="showList1Data()"
        class="md-primary">List1</button>

<!-- list 2 button -->
<button md-button
        (click)="showList2Data()"
        class="md-primary">List2</button>

<md-content>
<h1 align="center">{{title}}</h1>
<h2>lists:</h2>
<div *ngIf="showingList1">
    <div class="list-bg"  *ngFor="#bulk of list1Data | async">
        ID: {{bulk.id}} Number of Items: {{bulk.numberOfItems}}
    </div>
</div>
<div *ngIf="showingList2">
    <div class="list-bg"  *ngFor="#bulk of list2Data | async">
        ID: {{bulk.id}} Number of Items: {{bulk.numberOfItems}}
    </div>
</div>
</md-content>