Is it possible that using the component getter to display a router link may not be effective?

My email application is being developed using angular 6, featuring a list of mailboxes for users to access by clicking on the provided link.

Interestingly, when utilizing component version A to display the mailbox list, clicking on the router link does not trigger any route, whereas version B functions perfectly as expected. Both version A and version B deliver the UI flawlessly. I'm left wondering about the mechanisms behind this behavior - is it the correct function of the getter accessor, or possibly a bug within Angular?

Angular version: 6.1.8
Browser: Chrome (desktop) version 69
Node version: v10.7.0
Platform: Mac

component (version A)

import { Component } from '@angular/core';
import { EmailService } from '~/email/services/email.service';

@Component({
    templateUrl: '../views/email.view.html',
})
export class EmailComponent {

    public constructor(private emailService: EmailService) {}

    public get mailboxes(): Mailbox[] {
        return this.emailService.mailboxes;
    }
}

component (version B)

import { Component, OnInit } from '@angular/core';
import { EmailService } from '~/email/services/email.service';

@Component({
    templateUrl: '../views/email.view.html',
})
export class EmailComponent implements OnInit {

    public mailboxes: Mailbox[];

    public constructor(private emailService: EmailService) {}

    public async ngOnInit(): Promise<void> {
        this.mailboxes = this.emailService.mailboxes;
    }
}

service

@Injectable()
export class EmailService {

    public get mailboxes(): Mailbox[] {
        return [
            { name: 'Inbox', icon: 'inbox', link: 'inbox' },
            { name: 'Sent', icon: 'send', link: 'sent' },
            { name: 'Drafts', icon: 'drafts', link: 'drafts' },
            { name: 'Spam', icon: 'report', link: 'spam' },
            { name: 'Trash', icon: 'delete', link: 'trash' },
            { name: 'Archive', icon: 'archive', link: 'archive' },
        ];
    }
}

template

<mat-nav-list>
    <a mat-list-item *ngFor="let mailbox of mailboxes"
        [routerLink]="['mailboxes', mailbox.link]">
        <mat-icon matListIcon>{{mailbox.icon}}</mat-icon>
        <h4 matLine>{{mailbox.name}}</h4>
    </a>
</mat-nav-list>

updates

Find the demo link here: https://stackblitz.com/edit/angular-gitter-clsw1d

Answer №1

Initially, this may appear unusual, but in linking 2 getters together and consistently returning a new Array in your service, Angular can get caught in an infinite loop when checking for value changes. This occurs because the values are "never fixed" as your array always changes its reference (unlike the initial method). To resolve this issue, consider modifying your service as follows:

@Injectable()
export class EmailService {

    mailbox = [
            { name: 'Inbox', icon: 'inbox', link: 'inbox' },
            { name: 'Sent', icon: 'send', link: 'sent' },
            { name: 'Drafts', icon: 'drafts', link: 'drafts' },
            { name: 'Spam', icon: 'report', link: 'spam' },
            { name: 'Trash', icon: 'delete', link: 'trash' },
            { name: 'Archive', icon: 'archive', link: 'archive' },
        ];

    public get mailboxes(): Mailbox[] {
        return this.mailbox;
    }
}

By making these adjustments, the functionality will align with expectations.

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

Enhancing view with Typescript progressions

My current view only displays a loader.gif and a message to the user. I am looking to enhance the user experience by adding a progress indicator, such as "Processing 1 of 50", during the data update process. The ts class interacts with a data service layer ...

Building upon a React component with TypeScript, we are extending its functionality using a generic type and then leveraging this same generic type

In my component, I have a setup where it takes two props - node and patchCurrentNode. import { css } from '@emotion/react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import React, { PropsWithChildren, useStat ...

What steps do I need to take to create a pristine build of the Microsoft/VSCode source code?

Currently working on setting up a fresh development environment for microsoft/vscode. As a beginner in JS, TS, NPM, and Yarn, which specific command should I run in order to delete all build artifacts and output files and compile the code changes I made? ...

The interface locationProps was expecting 0 type arguments, but instead received 1

When passing a user object through the useNavigation object, I encounter an issue. Here is how I am doing it: let navigate = useNavigate(); const showUser = (user: UserProp): void => { navigate('view', { state: user }); } Af ...

The transmission of response packets in the Ionic BLE system during the process of

Currently in the process of writing to a characteristic in Ionic BLE. After a successful write, I should receive a response packet. However, I am unsure of how to access this packet. Although I receive a success callback after writing, I am unsure where to ...

I'm encountering an issue trying to apply array filtering with checkboxes using React hooks and TypeScript

Help needed! I'm facing an issue while trying to filter an array based on gender using checkboxes. The functionality works fine for the male checkbox but seems to fail when clicking on the female checkbox. Below is the code snippet from my App.tsx fil ...

Revving up the RxJS Engine: Unleashing the Potential of race

I'm currently working on implementing a unique input component that will execute a search when either the input value changes (with a debounce of 500ms) or when the enter key is pressed. My goal is to avoid emitting the search term twice - once on the ...

javascript + react - managing state with a combination of different variable types

In my React application, I have this piece of code where the variable items is expected to be an array based on the interface. However, in the initial state, it is set as null because I need it to be initialized that way. I could have used ?Array in the i ...

Angular is programmed to actively monitor the status of elements for enabling or

Seeking a solution to determine if an element is disabled in an Angular directive. Have attempted with host listeners, but no success yet. Directive: @HostBinding('attr.disabled') isDisabled : boolean; @HostListener("disabled") disabled() { ...

Nested HTTP requests in Angular using RxJS: Triggering component update after completion of the first HTTP request

I have a requirement to make two http requests sequentially. The values retrieved from the first call will be used in the second call. Additionally, I need to update my component once the first http request is completed and also update it once the second ...

The rendering of ReactJS context-api is not working as expected after receiving the data

This is a unique site built on next.js. To ensure both my Navbar component and cart page have access to the cart's content, I created a context for them. However, when trying to render the page, I encounter the following error: Unhandled Runtime Erro ...

Error: A cyclic dependency cannot be instantiated. The ApplicationRef ("[ERROR ->]") is occurring in the NgModule AppModule within ./AppModule@-1:-1

I recently implemented the following code in my app.module.ts file: providers: [ AppConfigService, { provide: APP_INITIALIZER, useFactory: (config: AppConfigService) => () => config.getAppConfig(), ...

Tips for showing the output of the avg function from MySQL in an Angular application

Upon running a query, I retrieved the following data in Json format stored in myDocData: data: [ RowDataPacket { updatedAt: 2020-01-03T18:30:00.000Z, email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail ...

Hiding the header on a specific route in Angular 6

Attempting to hide the header for only one specific route Imagine having three different routes: route1, route2, and route3. In this scenario, there is a component named app-header. The goal is to make sure that the app-header component is hidden when t ...

Error in Typescript: An element is implicitly assigned the 'any' type because a string expression is being used to index a different type

Hello everyone, I'm fairly new to TypeScript and I've been struggling to troubleshoot an error in my code. Can someone please assist me with solving this TypeScript error? I keep getting the error message: "Element implicitly has an 'any&a ...

Error: TypeError encountered during UI Runtime JSON conversion of Circular Data Structure

I'm facing an issue while attempting to parse and stringify certain JSON data. The error occurs on this specific line of code: this.copyOfColumns = JSON.parse(JSON.stringify(Object.assign([], this.columns))); Below is the complete @Input (using Ang ...

Angular 2: A guide to setting up `--module system --experimentalDecorators` flags in your project

I am encountering an issue while compiling my TypeScript file: app/app.component.ts import {Component} from 'angular2/core'; @Component({ selector: 'my-app', template: '<h1>Messenger</h1>' }) export clas ...

The string property I pass to the List component with the flexDirection style is meant to be implemented, but unfortunately, an error occurs

When passing a string property ("raw" | "column") to the List component which has a flexDirection style property, I encounter an error: Type '{ direction: String; }' is not assignable to type 'FlexDirection | undefined'. 7 | ...

What is the best way to display a collection of images in an HTML page?

I have a list of strings containing images. How can I display these images on a webpage using Angular? images: [ "https://images.oyoroomscdn.com/uploads/hotel_image/1097/340ea5ee01acc37f.jpg", "https://images.oyoroomscdn.com/uploads/hotel_image/1097 ...

Passing ternary values to variables in Angular: A brief guide

To handle the situation where this.nxsId is empty, I should pass null for the specified nxsId. public nxsId: any; // defined as any nxsId: this.nxsId ...