How to conditionally apply a directive to the same tag in Angular 4

I am implementing angular 4 and have a directive in my template for validation purposes. However, I would like to first check if a specific condition is true before applying the directive. Currently, my code looks like this:

<div *ngIf="groupCheck; else NoDirective" #Directive>
 <li [directive]="controlGroup"><a [routerLink]="['/account/search/', '']"
                    routerLinkActive="active">Accounts</a></li>
 <li [directive]="controlGroup"><a [routerLink]="['/orders', '']"
                    routerLinkActive="active">Orders</a></li>
 <li [directive]="DIFFERENT_GROUP"><a [routerLink]="['/report']" routerLinkActive="active">Reports</a>
                </li>
 <li [directive]="controlGroup"><a [routerLink]="['/anotherStuff']" routerLinkActive="active">Another Stuff</a></li>
</div>
<div *ngIf="!groupCheck; else Directive" #NoDirective>
 <li><a [routerLink]="['/account/search/', '']" routerLinkActive="active">Accounts</a></li>
 <li><a [routerLink]="['/orders', '']" routerLinkActive="active">Orders</a></li>
 <li><a [routerLink]="['/report']" routerLinkActive="active">Reports</a></li>
 <li><a [routerLink]="['/anotherStuff']" routerLinkActive="active">Another Stuff</a></li>
</div>

I am looking for a way to achieve something like this:

<li *NgIf="condition true add [directive]=controlGroup; else Don't add directive to this line/tag/element"><a [routerLink]="['/account/search/', '']"
                    routerLinkActive="active">Accounts</a></li>
 <li *NgIf="condition true add [directive]=controlGroup; else Don't add directive to this line/tag/element"><a [routerLink]="['/orders', '']"
                    routerLinkActive="active">Orders</a></li>
 <li *NgIf="condition true add [directive]=DIFFERENTGROUP; else Don't add directive to this line/tag/element"><a [routerLink]="['/report']" routerLinkActive="active">Reports</a>
                </li>
 <li *NgIf="condition true add [directive]=controlGroup; else Don't add directive to this line/tag/element"><a [routerLink]="['/anotherStuff']" routerLinkActive="active">Another Stuff</a></li>

This way, I can avoid rewriting the entire code for just one condition and eliminate the need for conditional div. Is there a way to accomplish this?

-----******UPDATE******----- @Allabakash provided me with a potential solution:

<button [attr.md-raised-button]="condition ? '' : null"></button>

My challenge now is that my directive (which I cannot access) removes the entire element if it receives null or a name not present in the method. Here's how it functions:

set checkGroup(hasGroups: string) {
    if (hasGroups) {
        this.AuthService.hasOtherGroups(hasGroups, false).subscribe(res => {
            if (!res) {
                this.el.nativeElement.parentNode.removeChild(this.el.nativeElement);
            } else {
                this.el.nativeElement.style.display = '';
            }
        });
    } else {
        this.el.nativeElement.parentNode.removeChild(this.el.nativeElement);
    }
}

So, my main question is: Is there a way to use this directive with a condition inside the <li> tag that allows me to apply the directive on the element, and if the result is null, prevent the directive from being applied, thus avoiding repeating the entire menu?

Thank you for your assistance :).

Answer №1

Consider these two options:

  • Include your condition within your directive to transmit data to it
  • You can also achieve the desired outcome by using ngIf on multiple elements:

    <div *ngIf="false"></div>
     <div *ngIf="true" myDirective></div>

Answer №2

Learn how to create a custom structural directive, pass in parameters, and execute custom logic within it... For example:

@Directive({ selector: '[myDirective]' })
export class MyDirective implements OnInit {
    private _config;

    @Input()
    set myDirective(config) {
        this._config = config
    }

    constructor(
        private templateRef: TemplateRef<any>,
        private viewContainer: ViewContainerRef
    ) {}

    ngOnInit() {
        if (this._config) {
            this.viewContainer.clear()
        } else {
            this.viewContainer.createEmbeddedView(this.templateRef);
        }
    }
}

This is just a sample, but you have the freedom to trigger any actions based on various events such as changes in Input, emission of observables, and more...

Implement the structural directive similar to how you would use ngIf...

<ng-container *myDirective="config"></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

Tips for reverting from Angular 7 to Angular 6

I attempted to switch from angular 7 back to angular 6 by executing the following npm commands: npm uninstall -g angular-cli npm cache clean npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32535c55475e53401f515e5 ...

Make multiple calls to gapi.auth2.init using varying client_id each time

I am currently working on a single web page (Angular 6 app) where an admin user can create different Google accounts. In order to obtain a backoffice code with grantOfflineAccess, I am utilizing gapi. However, there seems to be an issue when trying to set ...

Issue with Angular's BeforeLoginService causing route authorization to fail

Implementing Route Authorization in Angular-12, I have the following service: BeforeloginService: import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; i ...

The class instances are not invoking the decorators

I'm experiencing issues with my decorators. It seems that the decorators are not being invoked on every instance of the class. While I understand that decorators are called during declaration time, I am wondering if there is a way to call them for eac ...

Error: Unable to execute fields.map function while generating a dynamic sitemap using next-sitemap module

I'm in the process of creating a dynamic sitemap for my website and here's the code I'm using: import { GetServerSideProps } from 'next'; import { getServerSideSitemap, ISitemapField } from 'next-sitemap'; import { makeSl ...

What is the method for passing an element in Angular2 Typescript binding?

Is there a way to retrieve the specific HTML dom element passed through a binding in Angular? I'm having trouble figuring it out, so here is the relevant code snippet: donut-chart.html <div class="donut-chart" (donut)="$element"> ...

Using Ionic 2 to fetch JSON data and display it using ngFor

My script.php generates a JSON array with data from mySQL; The next step involves retrieving this JSON array via AJAX; I am looking to dynamically create divs using ngFor, but I'm unsure of how to handle the callback for the JSON array in the Ajax s ...

tips for creating a unique component with specialized features

I am struggling to integrate action buttons with specific actions in my custom component. It seems challenging to provide functions to my custom table, especially those that depend on the attributes of the table itself. You can take a look at this exampl ...

Primeng - Concealed dropdown values within a scrollable table header

Recently, I integrated Primeng p-table with a filter and frozen column feature (with one column being fixed while the others are movable). However, I encountered an issue with the select dropdown in the header. When I try to open the dropdown, the values a ...

Is there a way to trigger the opening of the mat-autocomplete panel when an option is selected in a different mat-autocomplete component?

Is it possible to trigger the opening of a mat-autocomplete panel when an option is selected in another mat-autocomplete? To see an example, please check out this demo. ...

The global CSS styles in Angular are not being applied to other components as expected

Currently utilizing Angular v10, I have a set of CSS styles that are meant to be used across the entire application. To achieve this, I added them to our global styles.css file. However, I'm encountering an issue where the CSS is not being applied to ...

Struggling to delete event listeners in TypeScript using object-oriented programming with JavaScript

After researching the issue, I have discovered that the onMouseUp event is being fired but it is not removing the EventListeners. Many individuals facing a similar problem fail to remove the same function they added initially. Upon reading information fr ...

"Capture the selected option from a dropdown menu and display it on the console: A step-by-step

Is there a way to store the selected value from a dropdown in a variable and then display it on the console? HTML <select class="form-control box" id="title" required> <option *ngIf="nationality_flag">{{nationality}}</option> &l ...

Angular2 - adding the authentication token to request headers

Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact t ...

Angular does not employ any Bootstrap styles when rendering

I have successfully installed both Ngb and Bootstrap 4 using the commands provided below, with the root module importing the package as well. npm install @ng-bootstrap/ng-bootstrap --save npm install bootstrap@next --save Within my code, I am attem ...

Angular - Executing a function in one component from another

Within my Angular-12 application, I have implemented two components: employee-detail and employee-edit. In the employee-detail.component.ts file: profileTemplate: boolean = false; contactTemplate: boolean = false; profileFunction() { this.profileTempla ...

What is the method in Angular 6 that allows Observable to retrieve data from an Array?

What is the method to retrieve data of an Array using Observable in Angular 6? ob: Observable<any> array = ['a','b','c'] this.ob.subscribe(data => console.log(data)); ...

Protractor syncing with an Angular page following redirection to an Auth0 non-Angular page

My Angular web application utilizes Protractor for end-to-end tests. Recently, I implemented OAuth0 authentication into my app. To disable Angular synchronization before redirecting to the non-Angular OAuth0 page, I use await browser.waitForAngularEnabled( ...

The @angular/cli ng serve command freezes after a period of activity

My experience with Angular development started with @angular/cli@5 and ng serve always ran smoothly. However, after updating to version 7.0.0 and creating a project with Angular 7.0.0, I encountered an issue where Angular stopped recognizing changes in fil ...

Tips for avoiding multiple reference paths in Angular TypeScript: - Simplify your imports

Setting up Typescript for an Angular 1.5 application has been a bit of a challenge. To ensure that a TS file can be compiled by gulp without any errors, I have to include the following line: ///<reference path="../../../../typings/angularjs/angular.d.t ...