-2

I would like to apply a class with col-md-9 if displaysidebar is true else class should be col-md-12

This is what i have tried but fails to work

<div class=" displaysidebar ? col-md-9 : col-md-12 ">

Where am i going wrong?

Geoff
  • 6,277
  • 23
  • 87
  • 197
  • 5
    https://angular.io/api/common/NgClass#how-to-use – Vega Aug 28 '17 at 18:42
  • 5
    Possible duplicate of [Assign classes conditionally in Angular2](https://stackoverflow.com/questions/39195742/assign-classes-conditionally-in-angular2) – Jota.Toledo Aug 28 '17 at 18:47

3 Answers3

4

You need to use NgClass along with property binding.

<div [ngClass]="displaysidebar ? 'col-md-9' : 'col-md-12'">
Daniel Gimenez
  • 18,530
  • 3
  • 50
  • 70
1

Can do in either way:

<div [ngClass]="{'col-md-9': displaysidebar, 'col-md-12': !displaysidebar} ">

or

<div [ngClass]="displaysidebar? 'col-md-9': 'col-md-12';">
Rajez
  • 3,717
  • 1
  • 14
  • 21
0

It should be something like

Template

 <div [ngClass]="(displaysidebar) ? 'col-md-9': 'col-md-12' ">

Component

   export class App {
      displaysidebar : boolean;
      constructor() {
        this.displaysidebar = true;
       }   

    }
Rahul Singh
  • 19,030
  • 11
  • 64
  • 86
  • dv is appreciated @jota haha, great way to support community now i guess – Rahul Singh Aug 28 '17 at 18:50
  • 2
    Rahul you are assigning string value to a boolean variable. – FAISAL Aug 28 '17 at 19:48
  • 1
    @Faisal thanks mate a typo my bad , had a spat with some one here thanks mate , i was editing it might have missed it . first it was like `sidebar ===" true" `. i changed to boolean missed that. – Rahul Singh Aug 28 '17 at 19:49