Increasing the number of service providers in Angular2-4 directives

Is there a way to apply both * to a string? Below is the code snippet I am working with:

<a class="sidenav-anchor" *ngIf="!item.hasSubItems()" md-list-item md-ripple [routerLink]="[item.route]" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
  <md-icon>{{ item.icon }}</md-icon>
  <span class="sidenav-item-name fade-in-on-icon-sidenav">{{ item.name }}</span><span fxFlex><!-- fill space --></span>
  <span class="badge fade-in-on-icon-sidenav" *ngIf="item.badge" [style.background-color]="item.badgeColor">{{ item.badge }}</span>
  </a>

I also need to add *showAuthed="false" to the <a> element.

Here is the showAuthed code:


import {
    Directive,
    Input,
    OnInit,
    TemplateRef,
    ViewContainerRef
} from '@angular/core';

import { UserService } from './services/user.service';

@Directive({ selector: '[showAuthed]' })
export class ShowAuthedDirective implements OnInit {
    constructor(
        private templateRef: TemplateRef<any>,
        private userService: UserService,
        private viewContainer: ViewContainerRef
    ) {}

    condition: boolean;

    ngOnInit() {
        this.userService.isAuthenticated.subscribe(
            (isAuthenticated) => {
                if (isAuthenticated && this.condition || !isAuthenticated && !this.condition) {
                    this.viewContainer.createEmbeddedView(this.templateRef);
                } else {
                    this.viewContainer.clear();
                }
            }
          )
      }

      @Input() set showAuthed(condition: boolean) {
          this.condition = condition;
      }

  }

You can find the complete code at https://github.com/gothinkster/angular-realworld-example-app and the sidebar design at

Answer №1

Here is a different approach:

// Utilize <ng-container> in ng7
<ng-container *ngIf="condition">
    <a class="link-item" *ngIf="isActive" mat-list-item [routerLink]="[item.route]" routerLinkActive="active">
        <mat-icon>{{ item.icon }}</mat-icon>
        <span class="item-name">{{ item.name }}</span><span fxFlex></span>
        <span class="badge" *ngIf="showBadge" [ngStyle]="{background-color: badgeColor}">{{ item.badge }}</span>
    </a>
</ng-container>

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

Ways to ensure that your Angular component.ts file is executed only after the body has completely loaded without relying on any external

I am attempting to add an event listener to an element created with a unique identifier using uuid, but I keep getting an error that states "Cannot read properties of null (reading 'addEventListener')" export class CommentItemComponent implements ...

Encountered an error while trying to install a package using NPM due to the requirement of 'require-from-string@

Every time I try to install a package (even nodejs), I encounter this issue. Here is what I have tried so far: Uninstalled all dependencies Cleared cache Reinstalled NPM / AngularCli Unfortunately, running any NPM command still results in the same error ...

Discovering ways to align specific attributes of objects or target specific components within arrays

I am trying to compare objects with specific properties or arrays with certain elements using the following code snippet: However, I encountered a compilation error. Can anyone help me troubleshoot this issue? type Pos = [number, number] type STAR = &quo ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

Is there a way to dynamically adjust the size of mat dialog content to match the size of the mat dialog in

I have adjusted the size of my mat dialog, but the content is still stuck at the original size. To illustrate, here are some images: https://i.stack.imgur.com/2lLV2.jpg After researching, I found that it can be resized using CSS. I attempted the followin ...

The identical package.json file is incompatible with both Windows and Mac operating systems, resulting in errors when

I encountered an error while trying to launch my app on Windows. basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") [0] ^^^^ [0] ^^^ [0] [0] SyntaxError: missing ) after argument list Can anyone provide insights on what m ...

Can a unique intrinsic type be created from scratch?

Ever since template literals were introduced in Typescript (PR), we've had access to various useful functions in our types: Uppercase Lowercase Capitalize Uncapitalize For more information, refer to the official documentation. Although it may seem ...

Descending order of index numbers

I have a table with indexing numbers and when I add a new row, I want the current value to be displayed in the top index number 2. However, my current code is displaying it as 0,1,2 instead of 2,1,0. Here is my HTML file: <mat-table #table [dataSource ...

What is the reason behind requiring {[param: string]: string | string[]} for the HTTP GET attribute [params]?

Problem Statement An error occurs during type inference in this.http.get() Error TS2322: Type 'Observable<ArrayBuffer>' is not assignable to type 'Observable<IInfo[]>'. Type 'ArrayBuffer' is missing the followin ...

Importing multiple features in Angular

[UPDATE]: Oops, my mind is a bit muddled from fatigue and I've mixed up two ideas which resulted in a rather meaningless question... Let's just blame it on the coffee! :P This may not be a pressing issue but more of a quest for knowledge... ...

Match and populate objects from the array with corresponding items

Currently, I have an array and object containing items, and my goal is to check each item in the array to see if its path matches any of the object names. If a match is found, I push it into that object's array. While this part is working fine, I am ...

Using the Moment library in a NestJS application

I am integrating momentjs into my nestjs application and I want to ensure that my services can be tested effectively. To achieve this, I have included momentjs in my module setup as shown below: providers: [ { provide: 'MomentWrapper', ...

Angular's text interpolation fails to update when a value is changed by an eventListener

I am encountering an issue with two angular apps, one acting as the parent and the other as the child within an iframe. The HTML structure is quite simple: <div class="first"> <label>{{postedMessage}}</label> </div> &l ...

What is the best way to incorporate a class creation pattern in Typescript that allows one class to dynamically extend any other class based on certain conditions?

As I develop a package, the main base class acts as a proxy for other classes with members. This base class simply accepts a parameter in its constructor and serves as a funnel for passing on one class at a time when accessed by the user. The user can spe ...

What is the best way to showcase a component using FlatList?

Discovering the power of React Native combined with TypeScript and Redux Toolkit Hello! I'm currently facing an issue with rendering a list of messages using FlatList. Everything renders perfectly fine with ScrollView, but now I need to implement inf ...

Currently, I am working with Angular 11 and encountered some errors while trying to embark on a new project

Command: ng serve Error: Cannot find module '@angular-devkit/build-angular/package.json' View details in "/tmp/ng-lQbnUK/angular-errors.log". These errors occurred when I tried to create the project: Installing packages (npm)... npm WARN depreca ...

Navigating through a mergeMap observable with an undefined value

In my Angular 6 app, I have a class that attaches API tokens to every http request using the getIdToken() method. If the token retrieval is successful, everything works fine. However, if it fails, my app will stop functioning. I need help with handling th ...

Is it possible to retrieve a union type property as an array of values in order to conduct a flexible type validation process?

Currently, my code looks something like this: interface Apple { type: 'Apple' } interface Banana { type: 'Banana' } interface Coconut { type: 'Coconut' } type Fruit = Apple | Banana | Coconut type AppleOrBanana = App ...

How to utilize TypeScript fetch in a TypeScript project running on node with Hardhat?

During a test in my hardhat project on VSCode, I encountered the need to retrieve the metadata object of my NFT from a specified URL. Initially, I assumed I would have to import fs to read the URL. However, while typing out the method, I impulsively opted ...

The mat select option does not have the correct width for the mat

Can someone please help me with this issue? I'm having trouble with the width of the options in a mat-select within a form. When I try to select an option, the width extends to 100% instead of staying within the select box. Here is a snapshot showing ...