Search code examples
angularngx-bootstrap

How do square brackets determine the class in angular 2


I was just going through an Angular 4.0 component online on the ngx GitHub repo, basically just the header component as can be seen below:

<div class="header-container"
     [class.left]="position === 'normal'"
     [class.right]="position === 'inverse'">
  <div class="logo-containter">
    <a (click)="toggleSidebar()" href="#" class="navigation"><i class="nb-menu"></i></a>
    <div class="logo" (click)="goToHome()">ngx-<span>admin</span></div>
  </div>
  <ngx-theme-switcher></ngx-theme-switcher>
</div>

The thing is i am not quite able to understand the way the class code works , i see the below code and am not quite able to understand it:

[class.left]="position === 'normal'"
[class.right]="position === 'inverse'"

What exactly does the code above really do ?

The typescript file for the header component looks like so:

import { Component, Input, OnInit } from '@angular/core';

import { NbMenuService, NbSidebarService } from '@nebular/theme';
import { UserService } from '../../../@core/data/users.service';
import { AnalyticsService } from '../../../@core/utils/analytics.service';

@Component({
  selector: 'ngx-header',
  styleUrls: ['./header.component.scss'],
  templateUrl: './header.component.html',
})
export class HeaderComponent implements OnInit {


  @Input() position = 'normal';

  user: any;

  userMenu = [{ title: 'Profile' }, { title: 'Log out' }];

  constructor(private sidebarService: NbSidebarService,
              private menuService: NbMenuService,
              private userService: UserService,
              private analyticsService: AnalyticsService) {
  }

  ngOnInit() {
    this.userService.getUsers()
      .subscribe((users: any) => this.user = users.nick);
  }

  toggleSidebar(): boolean {
    this.sidebarService.toggle(true, 'menu-sidebar');
    return false;
  }

  toggleSettings(): boolean {
    this.sidebarService.toggle(false, 'settings-sidebar');
    return false;
  }

  goToHome() {
    this.menuService.navigateHome();
  }

  startSearch() {
    this.analyticsService.trackEvent('startSearch');
  }
}

Solution

  • It is short hand syntax to apply a conditional css class to an element.

    [class.left]="position === 'normal'"
    

    Would apply the css class left to the element if the position === 'normal' evaluates to truthy and otherwise it would not apply the class.

    See the Template syntax documentation as a reference.

    Also here the syntax documentation from the cheat sheet

    <div [class.extra-sparkle]="isDelightful">
    

    Binds the presence of the CSS class extra-sparkle on the element to the truthiness of the expression isDelightful