Correct way for manipulating/referencing DOM elements in Angular

Viewed 61

I have the following ion-segment HTML code:

<ion-segment (ionChange)="segmentChanged($event)" scrollable>
    <ion-segment-button checked value="calendar">
        <ion-icon name="calendar"></ion-icon>
    </ion-segment-button>
    <ion-segment-button  value="list-box">
        <ion-icon name="list-box"></ion-icon>
    </ion-segment-button>  
</ion-segment> 

<ion-card [hidden]="true">
    test
</ion-card>
<ion-card>
    test
</ion-card>

I want to swap which card becomes visible when I press the segment button. Now I could easily fix this using Jquery, but I want to do this without JQuery.

I have the following event, which is being triggered correctly atm:

segmentChanged(): void { console.log("I triggered") }

What is the best (or a good) way to implement this functionality?

1 Answers

You can prepare your tabs in the component, display them with a for loop in the template and save in a property currently selected tab. Then it won't be a problem to watch the data automatically.

export interface Tab {
    code: string;
    name: string;
    icon: string;
}

...

// your component ts file
tabs: Tab[] = [
    {
        code: 'first',
        name: 'First tab',
        icon: 'first-icon',
    },
    {
        code: 'second',
        name: 'Second tab',
        icon: 'second-icon',
    },
];
currentTab: Tab = tabs[0];

segmentChanged(tab: Tab): void {
    this.currentTab = tab;
}


// template html file
<ion-segment scrollable>
    <ion-segment-button *ngFor="let tab of tabs" value="calendar" (click)="segmentChanged(tab)">
        <ion-icon [name]="tab.icon"></ion-icon>
    </ion-segment-button>
</ion-segment> 

<ion-card *ngFor="let tab of tabs">
    <ng-container *ngIf="tab.code === currentTab.code">
        {{ tab.name }}
    </ng-container>
</ion-card>
Related