I’m new to Angular 17 and I’ve noticed that every time I want to use an ngClass attribute or an ngStyle I get an error like it doesn’t recognize them and I get this error
NG8002: Can’t bind to ‘ngClass’ since it isn’t a known property of ‘p’.
atributte.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-atributo',
standalone: true,
imports: [ ],
templateUrl: './atributo.component.html',
styleUrl: './atributo.component.css'
})
export class AtributoComponent {
messageType = 1
}
attributte.component.html
<p [ngClass]="{'info' : messageType === 1, 'error' : messageType !== 1 }">Mensaje importante</p>
Do you know if the import is okay or should I import something else?
Thanks ins advance
Then notice that if I add it works with ngClass but not working with ngStyle
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-attribute',
standalone: true,
imports: [CommonModule],
templateUrl: './attribute.component.html',
styleUrl: './attribute.component.css'
})
2
Answers
ngClass
&ngStyle
are directives.Directives need to be imported in standalone components to be instantiated.
Unlink with component with selectors, directive can match anything from attributes to tags. This means the framework doesn’t throw an error when a directive is not imported in a standalone component.
HTML
ts
please check this stack blitz link
https://stackblitz.com/edit/github-tvhx5n-p1zh8q?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fhome-page%2Fhome-page.component.html,src%2Fapp%2Fhome-page%2Fhome-page.component.ts