Error: ModuleInjectorIssue(MainApp)[NgIf -> ElementRef]

After creating a Directive in Angular7, I encountered an error when trying to use it:

Error: StaticInjectorError(AppModule)[NgForOf -> TemplateRef]: StaticInjectorError(Platform: core)[NgForOf -> TemplateRef]: NullInjectorError: No provider for TemplateRef! Error: StaticInjectorError(AppModule)[NgForOf -> TemplateRef]: StaticInjectorError(Platform: core)[NgForOf -> TemplateRef]:

The directive was created within the SharedModule:

@NgModule({
  declarations: [FilderrorComponent, UploadfileComponent, ImageComponent, ValidatePermissionDirective],
  imports: [
    CommonModule
  ],
  exports: [ FilderrorComponent, UploadfileComponent, ImageComponent, ValidatePermissionDirective]
})
export class SharedModule {

    static forRoot(): ModuleWithProviders {
      return {
        ngModule: SharedModule,
        providers: [ FilderrorComponent, UploadfileComponent, ImageComponent , ValidatePermissionDirective]
      };
  }
}

This is the code for the Directive:

@Directive({
  selector: '[appValidatePermission]'
})
export class ValidatePermissionDirective implements OnInit {

  show: boolean;
  constructor(private templateRef: TemplateRef<any>,
              private viewContainerRef: ViewContainerRef
    ,         private dynamic: DynamicPermissionService) { }

  // tslint:disable-next-line:no-input-rename
  @Input() AccessName: string;

  ngOnInit() {
    this.ValidatePemission();
    if (this.show) {
      this.viewContainerRef.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainerRef.clear();
    }
  }
  ValidatePemission() {
    console.log('AccessName : ', this.AccessName);
    const find = this.dynamic.dynamicModel.find(x =>
      !! x.actionsVM.find(z => z.actionEnglishName === this.AccessName));
    console.log(find);
    if (find) {
        console.log(true);
        this.show = true;
      } else {
        console.log(false);
        this.show = false;
      }
  }
}

The shareModule was defined in the AdminModule :

@NgModule({
  declarations: [],
  imports: [
    SharedModule,
    AdminpanelRoutingModule,

  ],
  providers: [Toolkit, { provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }]
})
export class AdminpanelModule { }

The Directive was used in HTML as follows:

<span [appValidatePermission]="CreateRole">
  <router-outlet></router-outlet>
</span>

I am facing an issue with this implementation. Can anyone help me solve it?

Answer №1

In my opinion, the issue stems from the templateRef being null. Consider initializing it before utilizing it

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

Angular: Transforming input types

When the div is pressed, it triggers a function that changes the type of input. There are two password inputs that are changed to text when the function is triggered. Issue Error 1: 'password' may be null. If I enter '' in the password ...

Creating a new image by extracting a specific HTML div tag that contains an image and its layers

I currently have a div element that includes an image element along with multiple other div elements containing small text displayed above the image. I am looking to save the image along with its content to a new image file. Any suggestions or ideas are ...

Having trouble executing cucumber tests using protractor

Whenever I run my tests, I keep encountering the error: TypeError: e.getContext is not a function I am utilizing examples from https://github.com/cucumber/cucumber-js, making some modifications in world.js (to resolve timeout issues) Application versions ...

The Viewchild element is currently nonexistent

(Angular 9) I'm having issues with using ViewChield() in my code. Here is a snippet of the HTML I am working with: <input type="text" pInputText [(ngModel)]="code" #inputStudent/> Here is what I have in my TypeScript file: ...

The Zoom-sdk functions properly on a local machine, but encounters issues when it is

Using zoom's API, jwt, and the websdk, I am able to create a meeting on button click, join as a host, and start the meeting for others to join. This process works flawlessly when running locally, but once deployed to Cloudflare, I encounter the follow ...

Is there a way to receive information from the server without the need to press the "submit" button?

Below is a message I have: <h3 id="welcomeUsername">Hello, </h3> I am looking to trigger this script: function loadPage(){ $.get( "/fetchUser", function( data ) { $( "#welcomeUsername" ).append( data ); alert ...

Can one extract the content from a secure message received from a Telegram bot?

Currently, I am utilizing the sendMessage() function with protected_content: true in order to prevent Telegram users from forwarding my bot's messages to others. Prior to implementing this setting, the text below was easily copyable. However, after e ...

Looking to perform multiple asynchronous calls to a single endpoint using Angular 8

I am faced with a challenge where I need to use a GET call that only accepts one search number, but I require the ability to search using multiple numbers through the same endpoint. While I know this can be solved by creating a new endpoint with a POST cal ...

What is the best way to create a generic function parameter for a single property of an object?

I am trying to refactor a generic function into accepting parameters as a single object function test<T>(a: string, b: T, c: number) Instead, I want the function to receive an object like this: function test(params: {a: string; b: T, c: number}) I ...

When does 'ng-if="true" + data-ng-if="true" equal false?

It's interesting to note that when utilizing ng-if="truthyValue" and data-ng-if="truthyValue" within an HTML element in the context of AngularJS version +1.6, the element in question will not be rendered in the DOM. This holds true even if ng-if and d ...

Steps for verifying the presence of an element in Selenium using JavaScript

I'm facing an issue with a Jest and Selenium test. I'm trying to verify if an element is removed from the DOM after being clicked. Here's what I've attempted: test('User removes button after clicking on it', async (done) =& ...

Module not found error: Immutable-ext module is missing

After installing Immutable-ext: const { List } = require("immutable-ext"); const one = ["one", "two", "three"]; const two = ["one", "four", "five"]; An error is returned stating: Error: Cannot find module 'immutable' at Function.Module._r ...

Dynamic Formatting with Vue JS: Enhancing Phone Number Input

I am working on a form that includes a phone number input field, and I want the formatting of the number to change to a standard telephone number format as the user types. Can someone provide guidance on how this can be achieved using JavaScript and Vue 3? ...

Assign a value to the input field based on changes made in another input field

I am brand new to the world of JavaScript and currently grappling with setting a value in an input field based on the onchange event of another input field. Here is my code sample for input field 1: <input type='text' onchange='methodTh ...

Incomplete DOM elements in jQuery are like puzzles that need to be solved

My issue revolves around jQuery and manipulating DOM elements. I need a specific template setup, as shown below: var threadreply = " <li class='replyItem'>" + " <div class='clearfix'>" + ...

Retrieving the URL of a previous page in a Nest.js server

In our application, we utilize Angular 8 for the user interface and Nest Js server. One challenge we are facing is that when navigating to different pages within the application, the page URL includes a port number. While I am able to access this page UR ...

Using the PATCH method in Rails instead of POST

i have some code to display here <%= form_for @campaign, url: brands_campaign_path(@campaign), method: :patch, :html => {:multipart => true, :class => 'form-horizontal'} do |f| %> and it generates the following <form class ...

Searching through data fields in MongoDB that have been filled with information

In my Mongoose queries, I am dealing with models known as "Activities" that have a specific schema structure. This schema includes fields such as actor, recipient, timestamp, activity, event, and comment. var activitySchema = new mongoose.Schema({ act ...

Encountering a NextJS error when attempting to access a dynamic route

I am currently working on a Next.js application that involves dynamic routing. I have encountered an error message stating: Error: The provided path X0UQbRIAAA_NdlgNdoes not match the page:/discounts/[itemId]`.' I suspect that the issue may be relat ...

Firebase is not updating the number

Having just started with Firebase, I have been following all the guidelines for web Firebase auth. I have successfully managed to login, log out, and update all data except for the phone number. Despite receiving a success message in the console, my phone ...