anderlaini
anderlaini

Reputation: 1821

Ionic 4 - easiest way to a button add/remove component from page

I'm using page variables to add/remove components from my page.

This sounds weird but it actually works.

mypage.html

<pop-product *ngIf="this.pop_product_open" [data]="this.pop_product_data"></pop-product>

mypage.ts

public pop_product_open:boolean = false;
public pop_product_data:any = null;

...

async openPopProduct(product){
  this.pop_product_open = true;
  this.pop_product_data = product;
}

Is there any other/simplest/better way to add/remove component from the page?

I'm asking cause I'm going to have about 15 components and it's scary how messy the code is going to be on managing lots of variables this way.

Upvotes: 1

Views: 227

Answers (1)

Tomislav Stankovic
Tomislav Stankovic

Reputation: 3128

In case of having more than for example two pages, you can use something like this.

First, you need to have one function for selecting the component that you want to show.

example.ts

selectedPage: string = 'DefaultPage';

exampleFunction(page){
  this.selectedPage = page;
}

And then, that component will be shown. As a default, you can show some sample data if a specific component doesn't yet exist (!selectedPage).

exapmle.html

<ion-content>
    <map *ngIf="selectedPage == 'Map'"></map>
    <offers *ngIf="selectedPage == 'Offers'"></offers>
    <restaurants *ngIf="selectedPage == 'Eat'"></restaurants>
    <emergencies *ngIf="selectedPage == 'Emergencies'"></emergencies>
    <drink *ngIf="selectedPage == 'Drink'"></drink>
    <spa *ngIf="selectedPage == 'Spa'"></spa>
    <attractions *ngIf="selectedPage == 'Attractions'"></attractions>
    <beaches *ngIf="selectedPage == 'Beaches'"></beaches>
    <ion-row *ngIf="!selectedPage || selectedPage == 'DefaultPage'">
...

Upvotes: 1

Related Questions