0

Looking for good practices about angular folder structure I stumble upon this piece of code:

content-layout.component.html:

<div [class]="theme">
  <div class="mat-app-background">
    <app-nav></app-nav>

      <div class="container">
        <router-outlet></router-outlet>
      </div>

    <app-footer></app-footer>
  </div>
</div>

As far as I understand, the class tag is used to bind this component HTML with a CSS class. But the square brackets caught my attention, is there any real difference between the [class] and class for css binding? I can't hit the correct search term/feature name to google it myself

Rod Ramírez
  • 1,138
  • 11
  • 22

3 Answers3

2

the brackets [] indicate that the value is a property in your component, so instead of saying apply the class theme to the element, it will look for a property theme in your component and use whatever is stored in there.

class="theme" // apply class theme

    // Component
    public theme = 'theme';

    // HTML
    [class]="theme" // use what's stored in property "theme"

    or

    [class]="'theme'" // use string 'theme'
  • To further expand on this answer, Angular refers to this as "binding." Square brackets on their own represent one-way binding but two-way binding is also possible. See here for more info: https://angular.io/guide/binding-syntax – Luke Aug 11 '20 at 12:51
1

what you understood about class is right, where coming to [class], based on the value, class will be applied to that element. if the value is true or some value then that class will be applied to that element or else it will ignore that class. so basically you are using a specific class for some functionality and not using it for another

eg: <div [class.classOne]="true"></div> // now div element will have classOne class because result is true or some value.

references for better understanding about classes: https://angular.io/api/common/NgClass,

Difference between [ngClass] vs [class] binding

1

[] is a way to bind the data between ts and HTML, so in this case, the theme is a variable, on the other side container is a direct property

OAH
  • 1,160
  • 2
  • 11
  • 24