Creating conditional routing in an Ionic 3 Lazy module with dynamic page navigation

In my lazy loading Ionic 3 app, I have three different pages: "LoginPage," "VideoPage," and "HomePage." On the VideoPage, there is a checkbox that allows users to choose whether to show the video on the next start. The routing flow is as follows:

"LoginPage ==> VideoPage ==> HomePage" (checkbox clicked)

"LoginPage ==> HomePage" (checkbox not clicked)

The app should remember the user's choice even if they return after a long time, possibly using storage values. The LoginPage also features key value logic using storage, which is shown in the code snippet below:

(It might be possible for the VideoPage to output an event/variable to guide the login page on whether to go to the HomePage or VideoPage. I am exploring this approach.)

PS: Feel free to ask any questions or provide suggestions.

Login.html:

<ion-item no-lines>
      <ion-label floating>Password</ion-label>
      <ion-input type="password"></ion-input>
    </ion-item>

    <button class="charlotte-button" ion-button icon-left (click)="login()">
      <ion-icon class="picto picto-checkbox-active-w"></ion-icon>
      Login
    </button>

Login.ts:

export class LoginPage {  
   public password: string = '';
   public key: string = 'username'; 

   constructor(
    public navCtrl: NavController, 
    public storage: Storage, 
    private alertCtrl: AlertController ) {

    }

  login() {
     if (this.password === this.key) {
      this.storage
    .set(this.key, this.password)
    .then(val => this.navCtrl.setRoot('LoginPage'));
    } else {
      let alert = this.alertCtrl.create({
       title: 'Wrong password try again !',
       buttons: ['Dismiss']
      });
     alert.present();
    }
  }
}

Video.html:

<div class="video-container">
  <video controls>
   <source src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4" 
          poster="https://peach.blender.org/wp-content/uploads/title_anouncement.jpg?x11217"
          type="video/mp4">
   </video>
  <div class="video-title">Tutorial</div>
  </div>

  <ion-item no-lines class="checkbox-container">
    <ion-label class="diLabel">Show this video at the next start</ion-label>
    <ion-checkbox [(ngModel)]="disableVideo"></ion-checkbox>
  </ion-item>

Video.ts:

export class VideoPage { 

  constructor(public navCtrl: NavController, public navParams: NavParams) {}

 checkClicked() {

   if(this.disableVideo) {
     this.navCtrl.setRoot('VideoPage');
   } else {
     this.navCtrl.setRoot('Homepage');
   }
 }
}

Home.html: home.ts: No additional code is provided here as it does not directly relate to the current topic.

Answer №1

Is there a specific method in place to determine whether the user has checked the video checkbox? Must the user log in each time, without storing any tokens or verification of previous logins?

If logging in is necessary every time, the checkbox status should be verified on the login page. Storing this information using Storage is recommended, as demonstrated in your code snippet. Using events or behaviorSubjects may not work effectively since the user's preference for displaying the video page needs to be persisted. Here's how you can structure it:

video.html:

<ion-item no-lines class="checkbox-container">
  <ion-label class="diLabel">Show this video at the next start</ion-label>
  <ion-checkbox [(ngModel)]="disableVideo" (change)="changeCheckbox()"></ion-checkbox>
</ion-item>

video.ts

export class VideoPage { 
  public disableVideo: boolean = false;

  constructor(public navCtrl: NavController, public navParams: NavParams, public storage: Storage) {
    storage.get('yourCheckboxStatus').then(check => this.disableVideo = check);
  }

  changeCheckbox = () => this.storage.set('yourCheckboxStatus', this.disableVideo);

  checkClicked() {
    if(this.disableVideo) {
      this.navCtrl.setRoot('VideoPage')
    } else => {
      this.navCtrl.setRoot('AcceuilPage')
    }
  }
}

You'll need to implement this logic when the user logs in:

login() {
  if (this.password === this.key) {
    this.storage
      .set(this.key, this.password)
      .then(val => {
        this.storage.get('yourCheckboxStatus').then(check => {
          if(check) this.navCtrl.setRoot('VideoPage')
          else this.navCtrl.setRoot('HomePage');
        });
      });
  } else {
    this.alertCtrl.create({
      title: 'Wrong password try again !',
      buttons: ['Dissmiss']
    }).present();
  }
}

If recurring logins are not required or if initialization checks are needed, include this logic in your app.components file.

Answer №2

If the term Next start refers to the next time the app is launched and the Video Page is displayed as a modal,

In the file video.ts

export class VideoPage { 

  constructor(public navCtrl: NavController, public navParams: NavParams, public storage:Storage) {}

  checkClicked() {
    if(this.disableVideo) {
      this.storage.set('showVideo',false)
    }
    else() => {
      this.storage.set('showVideo',true)
    }
  }
}

In the file login.ts

export class LoginPage {
  public password: string = '';
  public key: string = 'username'; 

  constructor(
    public navCtrl: NavController, public storage: Storage, private alertCtrl:AlertController, public modalCtrl:ModalController) {}

  login() {
     if (this.password === this.key) {
       // skipping the storing of password
       this.storage.get('showVideo').then((showVideo) => {
          if(showVideo){
            let modal = this.modalCtrl.create('VideoPage');
            modal.onDidDismiss(data => {
              this.navCtrl.setRoot('HomePage'))
            });
            modal.present()
          }else{
            this.navCtrl.setRoot('HomePage'))
          }
       }).catch(()=>{
         this.navCtrl.setRoot('HomePage'))
       });
     }else{
       let alert = this.alertCtrl.create({
         title: 'Incorrect password, please try again!',
         buttons: ['Dismiss']
       });
       alert.present();
     }
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 2: Shared functions for universal component usage

I am working on an Angular 2 webpack project and I have come across a scenario where I have some functions that are repeated in multiple components. I want to find a way to centralize these functions in a "master" class or component so that they can be eas ...

Is it possible to transfer an HTML template from one Angular 2 component to another component?

Imagine having a foundational component called CardComponent that is reusable, meaning it can accept inputs like: 1. DataArray 2. HTML template (that is iterated over) The consumer component will utilize the CardComponent selector and provide both the da ...

Different Ways to Modify the Appearance of Angular's mat-slide-toggle and mat-checkbox

I am facing an issue in my Angular form where I have a select box containing objects derived from database records. The goal is to automatically populate the form with the object values once one is selected. My Angular application includes an array of obj ...

Challenges surrounding asynchronous functionality in React hooks

I've been facing some issues with this code and have resorted to debugging it using console.log(). However, the results I'm getting are not making any sense. Can someone help me identify what's wrong with this code? I noticed that my console ...

Encountering issues with Angular 4 routing functionality in production environment

Everything seems to be functioning well with the routing in my Angular 4 web-app on my development setup, and the menu redirections are working smoothly in the live version. However, I have encountered an issue where the development version redirects to d ...

Should we rethink our approach to styling components in this way?

Is this approach using styled-components, nextjs, typescript, and react flawed or potentially problematic in terms of performance? The goal was to create a component that is initially unstyled but can receive CSS styles for each HTML element within the com ...

There is no varying factor between the platforms when utilizing ionic 3

My initial attempt at trying ionic 3 has been met with some challenges. When I launch the application using either the ionic lab or ionic serve command, the platforms displayed in the browser show the same views for every device (iOS, Android, Windows). H ...

Utilizing Highcharts/Highstock for handling large volumes of data efficiently

Dealing with a growing amount of data daily (currently over 200k MySQL rows in one week), the chart loading speed has become quite slow. It seems like using async loading is the solution (http://www.highcharts.com/stock/demo/lazy-loading). I attempted to i ...

The filter becomes ineffective once I remove the input value

Check out this HTML table containing an input field that filters plans. https://i.stack.imgur.com/UfIw2.png I input the value => 1 The filter successfully works https://i.stack.imgur.com/CsQXh.png Removing the value (1) displays all recordings, tot ...

Creating a dynamic table with columns of fixed width in Angular on the fly

I am struggling to create a data table with fixed column widths (20% each). I have incorporated div elements in my table structure to enable dynamic row creation using Angular, but this has caused some design issues. My goal is for all rows to occupy 100% ...

Developing Unique Number Formatting in Angular 5 with TypeScript

I am in need of a solution to format numeric values in a specific way. Here is the criteria: If a number has no decimal places, leave it as is. If it has any decimal places, format it with 4 digits after the "," or "." Here are some examples: No Formatti ...

The user interface in Angular 7 does not reflect the updated values after subscribing

Upon examining the code provided, it is evident that the UI does not reflect the updated value even though the field is set correctly. I have attempted two different approaches but have not explored the change detection approach as I believe the current c ...

Issue detected: The <path> attribute d is expecting a numerical value

I am currently working on retrieving values from Firebase and calculating the means of those values by iterating through each path in Firebase and storing them in individual variables. After that, I divide the sum by the total number of checkCount. Howev ...

When using Framer Motion for page transitions alongside React Router DOM v6, the layout components, particularly the Sidebar, experience rerenders when changing pages

After implementing page transitions in my React app using Framer Motion and React-Router-DOM, I noticed that all layout components such as the sidebar and navbar were unexpectedly rerendering upon page change. Here's a snippet of my router and layout ...

Angular ngClass and ngIf directives failing to update upon alterations

In my current Angular project, I am working on a functionality where I need to dynamically change a class based on a variable without having to refresh the page. I have experimented with *ngIf/else and [ngClass] directives, which do work, but unfortunatel ...

Using StencilJS to Incorporate CSS/SASS Styles from node_modules

I'm currently facing a challenge in importing a CSS file containing variables from a node_modules package. Despite trying to replicate the process outlined in stencil.config.ts, the builds continue to end up in a different location than intended, leav ...

How to Resolve File Paths in CSS Using Angular 7 CLI

My assets folder contains an image named toolbar-bg.svg, and I am attempting to use it as the background image for an element. When I use background: url('assets/toolbar-bg.svg'), the build fails because postcss is unable to resolve the file. How ...

typescript: define the type of an object that behaves like a map

My current approach involves utilizing an object to store a map, where keys are strings and values are of a fixed type T. Upon looking up a key in the object, the type inference automatically assigns it the type T. However, there is a possibility that it ...

It is necessary to sign out users when a specific database value is set to false

Whenever a value in the firebase database is false, I need to shut down the app for maintenance purposes. A problem arises when the user is already logged in, as the function does not trigger unless I reload the app. I am looking for a way to trigger the f ...

Traverse through a firestore collection in a synchronous manner

I am currently working on a Firebase callable function that performs batch processing on documents within a collection. The process involves the following steps: Copying a document to a separate collection for archiving purposes Executing an HTTP reque ...