Mark Rajcok
Mark Rajcok

Reputation: 364727

No provider for TemplateRef! (NgIf ->TemplateRef)

I'm trying to show a checkmark if an answer is the accepted answer:

template: `<div ngIf="answer.accepted">&#10004;</div>`

But I get this error:

EXCEPTION: No provider for TemplateRef! (NgIf ->TemplateRef)

What am I doing wrong?

Upvotes: 355

Views: 210360

Answers (4)

user1749518
user1749518

Reputation: 1

This issue happens if there are 2 *ngIf added to a statement. I had similar code <div *ngIf="someCondition class="class-name" *ngIf"condition"> After removing one of them it worked.

Hope this would help

Upvotes: 0

melenchenkov
melenchenkov

Reputation: 225

it's a common misconception to miss a few syntaxes in writing the code , one such popular mistake everyone tries to make is not using * before ngIf , which when used makes angular compiler to read ngIf as template reference variable and checks for local reference for the variable which wont be found in the file. so please check for these mistakes and learn form them if possible

<div *ngIf="answer.accepted">&#10004;</div>

Upvotes: 5

Jonathan Duclos
Jonathan Duclos

Reputation: 130

So, I can help to understand what (and where) you made the mistake, but before it, we need to read the documentation:

Access a TemplateRef instance by placing a directive on an element (or directive prefixed with *). The TemplateRef for the embedded view is injected into the constructor of the directive, using the TemplateRef token.

You can also use a Query to find a TemplateRef associated with a component or a directive.

So:

  • When using [ngIf]="something" you must use <ng-template> to access the template ref (eg: when using <template> or <ng-template>);
  • Using *ngIf you can use it where you want 'cause the * garante the access to template ref(eg: when using <span> or <div>);

If you're using in your code something like <span [ngIf]="message"> {{message}}</span> you probably gonna get some error.

Upvotes: 13

Mark Rajcok
Mark Rajcok

Reputation: 364727

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Upvotes: 893

Related Questions