Search code examples
javascriptstencils

how to handle ngClass in stencils JS web components


I have made components in angular js 4, now i am trying to make the same component as a web components in stencils Js.

I have the angular code as below

<button [class]="classNames" (click)="toggleMasterButton()" 
[ngClass]="masterButtonActive ? _config.masterButtonClass :'-state-grey'">

I tried the code as below but unable to go resolve the ngClass and class properly as in the angular component. Any help will be appreciated.

<button  onClick={this.toggleMasterButton.bind(this)}
class={this.masterButtonActive ? this._config.masterButtonClass:'-state-grey'}>


Solution

  • I believe you want to update/toggle css class when the user clicks on the button.

    To update class which you want to reflect on UI, in stencils-js you need to decorate with @State

    You can read more about stenciljs.com doc

    In short, you need to update your code as below.

     import { State } from '@stencil/core';
    
     export class TodoList {
    
      @State() masterButtonActive:boolean = false;
    
    
       toggleMasterButton(){
            this.masterButtonActive= true;
         }
    
          render() {
            <button  onClick={this.toggleMasterButton.bind(this)}
               class={'mcf__btn ' + ( this.masterButtonActive ? this.config.masterButtonClass:   '-state-grey')}My button</button>
            }
       }
    

    Hope this will work for you.