Search code examples
javascriptangularangular5angular10angular4-forms

NgClass Error Angular (Can't bind to 'ngClass' since it isn't a known property of 'a')


I'm new to angular, and I'm trying to dynamically add a bootstrap class to my html, based on the active tab, however, I'm getting an error. Can you help me?

My error: Can't bind to 'ngClass' since it isn't a known property of 'a'

My html component code:

<div class="p-5 bg-white rounded shadow mb-5">
  <!-- Rounded tabs -->
  <ul id="myTab" role="tablist"
    class="nav nav-tabs nav-pills flex-column flex-sm-row text-center bg-light border-0 rounded-nav">
    <li class="nav-item flex-sm-fill">
      <a id="home-tab" href="#tab1" data-toggle="tab" role="tab" (click)="viewTabName('In')" aria-controls="home" aria-selected="true"
        [ngClass]="{active: activeTabName === 'In'}" 
        class="nav-link border-0 text-uppercase font-weight-bold">In</a>
    </li>

    <li class="nav-item flex-sm-fill">
      <a id="profile-tab" href="#tab2" data-toggle="tab" role="tab" (click)="viewTabName('Out')" aria-controls="profile" aria-selected="false"
      [ngClass]="{active: activeTabName === 'Out'}" 
        class="nav-link border-0 text-uppercase font-weight-bold">Out</a>
    </li>

  </ul>

My component.ts:

@Component({
  selector: 'app-tab',
  templateUrl: './app-tab.component.html',
  styleUrls: ['./app-tab.component.scss']
})
export class AppTabComponent implements OnInit {
   constructor(){}

  activeTabName: string = '';
viewTabName(tab: string){
    this.activeTabName = tab;
    console.log(this.activeTabName);
  }
}

My app.module.ts

@NgModule({ 
declarations: [AppTabComponent],
 imports: [
    CommonModule,
    BrowserModule,
    FormsModule,
    ReactiveFormsModule
]
})

Solution

  • Please put class name in quotation marks

    [ngClass]="{'active': activeTabName === 'In'}"
    [ngClass]="{'active': activeTabName === 'Out'}"