Toggle button based on json response in angular 2

风格不统一 提交于 2019-12-25 18:14:35

问题


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>


来源:https://stackoverflow.com/questions/46065764/toggle-button-based-on-json-response-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!