Toggle button based on json response in angular 2

2019-08-24 02:53发布

问题:

I am trying to toggle button based on backend response.If the response is Yes, toggle button should be ON, if the response is No, toggle button should be off. Below is my html code

          <div class="btn-group btn-toggle">
  <button class="btn btn-sm btn-default">ON</button>
  <button class="btn btn-sm btn-primary ">OFF</button>
</div>

Below is my component code, where i calling a get service which returns response either Yes or No.I am calling the service in ngOnit() because i want to check whether the response is Yes /No when the page loads.Upon research i came to know we can achieve this using ngclass, but i am not sure how to do that.

    ngOnInit() {
        this.service.getFlagStatus().toPromise().then((flagStatus => {
          this.flagStatus= flagStatus;

         //if(flagStatus == 'Yes'){
                  //toggle right

             // }else if (flagStatus == 'No') {
                //toggle left
             // }
        }));
      }

flagStatus variable has the response(Yes/No). Let me know if i am doing in the right way.

回答1:

Set right text in the component's code:

ngOnInit() {
    this.service.getFlagStatus().toPromise().then((flagStatus => {
      if(flagStatus == 'Yes'){
         this.text = 'ON';
      } else if (flagStatus == 'No') {
         this.text = 'OFF';
      }
    }));
  }

And pass it into the component's template (Angular/Interpolation):

<div class="btn-group btn-toggle">
  <button class="btn btn-sm btn-primary">{{text}}</button>
</div>

Also you may play with classes (Angular/Class binding):

<button 
    class="btn btn-sm" 
    [class.btn-default]="text == 'ON'" 
    [class.btn-primary]="text != 'ON'">{{text}}</button>