Angular traveler guide

I am currently in the process of developing navigation tools using a wizard for a web application.

At this stage, the wizard functionality includes 2 navigation buttons (back/next) on each page. Additionally, there is a request from the product owner to incorporate a top navigation panel that allows users to easily switch between pages without navigating throughout the entire site. To implement this panel, I am using RouterLink to generate links to specific pages.

However, there is a minor issue with my implementation. When I utilize the top navigation panel to move between pages and then try to use the navigation buttons, the navigation wizard function stops working correctly (the error message displayed is: "this.onNext is not a function at GeneralInfoComponent.next (generalinfo.component.ts:53)").

Below is the code snippet:

Generalinfo.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { EvaluationService } from '../evaluation.service';
import { InfoGeneral } from './model';
import { WizardComponent } from './../wizard/index';

@Component({
moduleId: module.id,
selector: 'generalinfo-cmp',
templateUrl: 'generalinfo.component.html'
})

export class GeneralInfoComponent {

@Input() onNext: any;

generalInfo:    InfoGeneral;
form:               FormGroup;
wizard:             ClaimStep;

constructor(
    private fb: FormBuilder,
    private evaluationService: EvaluationService
) {
        this.initForm();
        this.generalInfo = evaluationService.getGeneralInfo();
}


initForm() {
    this.form = this.fb.group({
        generalInfo: this.fb.group({
            consultantFirstName: ['', Validators.required],
            consultantLastName: ['', Validators.required],
            consultantPhone: ['', Validators.required],
            consultantEmail: ['', Validators.required],
            consultantWishedJob: ['', Validators.required],
            managerName: ['', Validators.required],
            consultantExperience: ['', Validators.required],
            consultantMinRemuneration: ['', Validators.required],
            consultantMaxRemuneration: ['', Validators.required],
            consultantAvailableDate: ['', Validators.required],
            consultantInterviewDate: ['', Validators.required],
            consultantInterviewHour: ['', Validators.required],
            consultantComment: ['', Validators.required]
        })
    });
}

next() {
        this.onNext();
}
}

RandomPage.component.html (to display the navigation panel links)

[...]
<a [routerLink]="['/dashboard/evaluation/generalinfo/']" skipLocationChange><span class="label">✓</span></a>
[...]

wizard.component.html

<generalinfo-cmp *ngIf="wizard.currentStep === 1" [onNext]="onNext"></generalinfo-cmp>
<matrice-cmp *ngIf="wizard.currentStep === 2" [onBack]="onBack" [onNext]="onNext"></matrice-cmp>
<entretienrh-cmp *ngIf="wizard.currentStep === 3" [onBack]="onBack" [onNext]="onNext" ></entretienrh-cmp>
<entretienmgr-cmp *ngIf="wizard.currentStep === 4" [onBack]="onBack" [onNext]="onNext" ></entretienmgr-cmp>
<entretiendir-cmp *ngIf="wizard.currentStep === 5" [onBack]="onBack" [onNext]="onNext" ></entretiendir-cmp>
<proposition-cmp *ngIf="wizard.currentStep === 6" [onBack]="onBack"></proposition-cmp>

wizard.component.ts

import { Component, Inject  } from '@angular/core';
import {  ClaimStep } from './wizard.service';

@Component({
  moduleId: module.id,
  selector: 'wizard-cmp',
  templateUrl: 'wizard.component.html',
  providers: [ClaimStep],
})

export class WizardComponent  {

wizard: ClaimStep;
constructor(private claimStep: ClaimStep) {
    this.wizard = claimStep;
}

onNext = () => {
    this.wizard.addStep();
}

onBack = () => {
    this.wizard.subtractStep();
}

onSwitch = () => {
            console.log(this.wizard.getCurrentStep());
    }
}

wizard.service.ts

import {Injectable} from '@angular/core';


@Injectable()
export class ClaimStep {
currentStep: number;

constructor() {
    this.currentStep = 1;
}

addStep(): number {
    return this.currentStep++;
}

subtractStep() {
    this.currentStep = this.currentStep - 1;
    return this.currentStep;
}

getCurrentStep() {
    return this.currentStep;
}
}

If you have any suggestions or solutions, they would be greatly appreciated.

Answer №1

It seems like there could be some issues related to the current context of 'this'.

Why don't you give this alternative approach a try:

onNext = (() => {
    this.wizard.addStep();
}).bind(this);

onBack = (() => {
    this.wizard.subtractStep();
}).bind(this);

Alternatively, you could consider using this method (instead of the previous recommendation):

... [onNext]="onNext.bind(this)" ...

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

Message within the boundary of the input field

Click here to view the image It would be great to have the text "text name" displayed on the border of the input box. Here is the HTML code - <input type="text" id="text creator" class="form-control" placeholder="text creator" na ...

Leverage specialized TypeScript typings with .d.ts files in Next.js (Error: Module cannot be found: Unable to resolve ...)

When using a JavaScript library that lacks @type definitions for TypeScript, I had to create my own .d.ts file named foo.d.ts. The project structure is as follows: ... .next/ pages/ ... typings/ foo.d.ts ... tsconfig.json In my VS Code editor, the def ...

Displaying a list of items in a dropdown menu that includes both the item's ID and name using angular

I am currently utilizing the angular2-multiselect-dropdown to connect with server values. interface PayerDummyObjType{ id: string; itemName: string; } PayerDummyObjType: PayerDummyObjType[]; PayerDummyObjTypeSelected: PayerDummyObjType[]; dropdownSettin ...

"Sorry, there was an issue with AmStockCharts when trying to update the chart: Unable to assign a value to the '

Currently, I am using Angular 4.3.6 along with TypeScript 2.4.2 for my project. The issue that I am facing involves reading data from a socket and attempting to add it to the dataprovider. I came across an example at: While implementing a serial chart, q ...

Creating a personal TypeScript language service extension in Visual Studio Code

Currently, I am working on developing a TSserver plugin in VSCode and struggling to get the server to load my plugin. I have experimented with setting the path in tsconfig.json to both a local path and a path to node_modules, but it still isn't worki ...

Save two pieces of data to a CSV file and import them into the AG Grid

There is an issue with exporting a grid that contains two and three datas in some cells to a CSV file. The columns for these data do not get exported, leading me to believe that there is a need for special code implementation when writing the columnKeys. H ...

The method toLowerCase is not found on this data type in TypeScript

I am currently working on creating a filter for autocomplete material. Here is an example of my model: export class Country { country_id: number; name: string; } When calling the web method ws: this.ws.AllCountry().subscribe( ...

Uploading a File using Angular HttpClient to CodeIgniter 3 API-Rest

I'm currently facing an issue while attempting to send a file from Angular-CLI to an API-Rest application built in Codeigniter3, as I am receiving an unknown error in response. Angular Code Service: constructor( private http: HttpClient) { } submitI ...

When attempting to send an email with nodemailer, an error message popped up saying "setImmediate is not defined."

let transporter = nodemailer.createTransport({ host: "sandbox.smtp.mailtrap.io", port: 2525, auth: { user: "xxxxxx", pass: "xxxxxx" }, tls: { rejectUnauthorized: false } ...

Dealing with enum values in Jest tests when using Prisma can be tricky. The error message "Group[] not assignable to

Here is an example of my prisma postgresql schema: model User { id Int @id @default(autoincrement()) uuid String @db.Uuid createdat DateTime @default(now()) @db.Timestamp(6) updatedat DateTime @updatedAt first ...

CDNify load error causing Grunt Serve to fail

I have encountered an issue with a freshly installed Angular project. When I try to run the grunt serve command, I receive the following error: I am currently using Node 12.6.1 with Source Tree and have confirmed that Bower is properly installed. Loading ...

Trouble with Implementing Nested h3 Styles in SCSS

I'm having trouble adjusting the margins of an h3 tag using scss in Angular. The scss code seems to be working, but when I nest the h3 tag inside a div tag, the margin adjustments don't take effect. Could someone help me figure out what's g ...

Utilizing ES6 Map type in TypeScript for Angular 2 Response Data Transfer Object Definition

Is it possible to utilize the es6 Map type in an HTTP Response DTO? Let's consider an Angular 2 request: public loadFoos(): Observable<FoosWrapper> { return this.http.get("/api/foo") .map(res => res.json()); } Now, take a loo ...

Trying out the combination of @inject parent and @contentChildren in practice

I have been working on developing a unique custom tab component that consists of both parent and children elements structured as follows: Parent @Component({ selector: 'app-custom-tabs', template: ` <div class="inline-flex"> ...

The error message "Unable to find 'encoding'" in NextJS is triggered by the use of try/require in the node_modules folder

Running a NextJS app in typescript with version 13.4.19, utilizing @apollo/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0d7e687f7b687f4d392334233e">[email protected]</a> triggers a warning during the build proce ...

Create a JavaScript random quote generator that produces a single quote every day

I have recently developed a random quote generator for my Angular application. The logic within the component is as follows: qotd = this.quotes[Math.floor(Math.random() * this.quotes.length)]; This code snippet fetches data structured like this: quote ...

I encountered a problem while trying to install Angular Material within my Nx workspace

Currently in the process of setting up an Angular and React project within a Nx monorepo workspace. Encountering trouble while attempting to install Angular Material using npm i @angular/material I'm running Angular v16. Below is the specific error me ...

Vue3 TypeScript may potentially have an object that is 'undefined'

This piece of code is Vue3 with TypeScript-based. export interface TenantDto { uuid: string; name: string; } export const useTenantStore = defineStore('tenant', { state: () => ({ tenants: [], }), actions: { setMyTenants: (pa ...

Is there a way to utilize Angular to sort by a specific element in an array?

I have a firebase document that I need to sort by the text field associated with the first element in the name array, which is the official name. https://i.sstatic.net/TVcC9.png Despite my efforts, the following code isn't producing the desired resu ...

Setting a specific time zone as the default in Flatpickr, rather than relying on the system's time zone, can be

Flatpickr relies on the Date object internally, which defaults to using the local time of the computer. I am currently using Flatpickr version 4.6.6 Is there a method to specify a specific time zone for flatpickr? ...