My code is simple, a button that shows a list but I don't understand the error that it throws me, it just says
ERROR Error: "StaticInjectorError(AppModule)[NgIf -> TemplateRef]:
StaticInjectorError(Platform: core)[NgIf -> TemplateRef]:
NullInjectorError: No provider for TemplateRef!"
what is the error in the code?
my component
import { Component, OnInit } from '@angular/core';
import { Pelicula} from '../modelo/pelicula';
@Component({
selector: 'app-lista-peliculas',
templateUrl: './lista-peliculas.component.html',
styleUrls: ['./lista-peliculas.component.css']
})
export class ListaPeliculasComponent {
public pelicula:Pelicula;
public mostrarDatos:boolean;
constructor() {
this.pelicula = new Pelicula(1, "El caballero de la Noche", "Christopher Nolan", 2008 );
this.anuncio();
this.mostrarDatos = false;
}
anuncio(){
console.log(this.pelicula);
}
botonMostrar(){
this.mostrarDatos = true;
}
}
and my html
<h2 class="titulo-lista">Listado de Peliculas</h2>
<button (click)="botonMostrar()">mostrar peliculas</button>
<ul ngIf="mostrarDatos === true">
<li>Pelicula: {{pelicula.titulo}}</li>
<li>Director: {{pelicula.director}}</li>
<li>Anio: {{pelicula.anio}}</li>
</ul>
The error is that you are not using the if directive correctly. You are missing the asterisk (*):
*ngIf
You have to fix it like this:
In the documentation they explain that the asterisk means that you are using a
directiva estructural
. The structural directives form and deform the HTML that you wrote in normal directives, but simplifying their use for better understanding of the code writer and for the reader. Behind all this Angular expands*ngIf
on the corresponding directives, which you can also use directly if you want to have full control, but they are not generally used.For example, your code can be rewritten as:
Which is exactly what Angular will do when compiling. But as you will see, there is not much benefit for you as a developer and less for the one who has to read your code.
I have rarely been forced to use directives directly. But if you understand English, it would be good if you read the documentation that I linked above. Understanding the use of structural directives, the use of
ng-template
andng-container
allows you to do other interesting things like reuse templates, write HTML that is more dynamic (look for the use of ngSwitch), etc.By the way, notice that I made a small change to your code from
<ul *ngIf="mostrarDatos === true">
a<ul *ngIf="mostrarDatos">
. You can play with*ngIf
it almost like you play withif (...)
normal JavaScript.You must be using the tag
<template>...</template>
in one of your component templates.Change the tag and use
<ng-template>...</ng-template>.