skip to Main Content

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


  1. ngClass & ngStyle are directives.

    Directives need to be imported in standalone components to be instantiated.

    @Component({
      selector: 'app-atributo',
      standalone: true,
      imports: [NClass, NgStyle],
      templateUrl: './atributo.component.html',
      styleUrl: './atributo.component.css'
    })
    export class AtributoComponent {
      messageType = 1
    }
    

    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.

    Login or Signup to reply.
  2. HTML

    <h1 class="font-black uppercase text-6xl md:text-8xl text-center py-8 px-4">
      <div [ngStyle]="true ? { color: 'red' } : { color: 'yellow' }">home page</div>
    </h1>
    

    ts

    import { Component } from '@angular/core';
    import { CommonModule } from '@angular/common';
    
    @Component({
      selector: 'app-home-page',
      standalone: true,
      imports: [CommonModule],
      templateUrl: './home-page.component.html',
      styleUrls: ['./home-page.component.scss']
    })
    export class HomePageComponent {
    
    }
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search