ChatGPT解决这个技术问题 Extra ChatGPT

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?


M
Mark Rajcok

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>.


The same excpetion can also occur if you use ngSwitchCase without the asterisk!
i wanted to upvote this, but i see that i already did a long time ago.
Couldn't the error-checker notice it starts with ng and add at the bottom: "ng__ found, did you mean *ng__ ?" (Maybe they think that's holding the dev's hand too helpfully.)
J
Jonathan Duclos

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 to access the template ref (eg: when using