Angular 10 custom directive file is not triggering on component loads

847 Views Asked by At

In my angular project, I have a custom directive to hide and show the button. I created the directive file and then imported the directive into the shared module.ts file. Components are also available in the shared module only. but on component load directive not loading and not even triggering. but it looks everything fine only. I couldn't able to find out the reason for this issue.

I imported sharedmodule.ts in app.module.ts and in console also there is not errors, components also rendering properly, but directive is not triggering.

Can you help me to fix this.

Directive File:

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { UserContextService } from '../../services/usercontext/user-context.service';
import { environment } from '../../../environments/environment';

@Directive({ selector: '[Customacl]' })
export class DataCustomaclDirective {
   constructor(private template: TemplateRef<any>, private viewContainer: ViewContainerRef, private userContext: UserContextService) { }

@Input()
set DataCustomacl(role: string) {
    debugger
    if (role) this.viewContainer.clear();
    else this.viewContainer.createEmbeddedView(this.template);
}
}

Component.html:

<button type="button" Customacl >Submit</button>

Shared.module.ts:

import { DataCustomaclDirective } from './directives/acl';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { SearchName } from './servicer.name.pipe';

@NgModule({
    imports: [CommonModule, FormsModule],
    declarations: [DataCustomaclDirective, ],
    providers: [SearchName],
    exports: [DataCustomaclDirective]
})

export class SharedModule {
   static forRoot(): ModuleWithProviders<SharedModule> {
       return {
        ngModule: SharedModule,
        providers: [AlertService]
      };
   }
}
1

There are 1 best solutions below

1
On

I created a reproduce version of your code stackblitz.

First of all, to do the logic as you want, your directive should be a structural directive that is use with the *, eg: *Customacl.

Its will throw error like Error: NG0201: No provider for TemplateRef found. ...

Secondly, the setter DataCustomacl will not trigger because you did not pass any data into your directive (you can check in the stackblitz code)