Home > database >  Angular Material button change colour based on server response
Angular Material button change colour based on server response

Time:07-11

I am trying to change the colour of the button based on some conditions. But for some reason it is not getting applied. My template code

<div >               
                    <button  mat-button  mat-raised-button type="button" (click)="startPrint(data.id)" 
                    [color]="job_status.get(data.id) == 'NEW' || 'START'? 'primary' : 'warn'" [disabled]="isDisabled">
                        <!-- <mat-icon>{{icon}}</mat-icon> -->
                        {{job_status.get(data.id) | translate}}                    
                    </button> 
                    {{job_status.get(data.id)}}        
                </div> 

My Component code

 ngOnInit(): void {
    console.log("---- Inside PrintJobComponent ngOnInit()-----");
    setTimeout(() => {
      this.pageTitleService.setTitle("Start Print Job");
    }, 0);

    this.coreService.getJobBoardContent().subscribe(
      (response) => {
        this.jobboardContent = response;
        console.log("Data: ", this.jobboardContent);
       
        this.jobboardContent.forEach(res => {
            console.log(res);
            this.job_status.set(res.id,res.job_status);
            //this.changeButtonState(res.id);
        });

        console.log("this.job_status MAP object::: ", this.job_status);
        console.log("this.job_status for id: " this.jobboardContent[0].id  " = "  this.job_status.get(this.jobboardContent[0].id));
        
        this.startProgressBar(this.jobboardContent[0].id);
      },
      (err) => {
        console.log(err);
      }
    );    
  }

enter image description here

CodePudding user response:

Can you make sure that you receive data from job_status.get(data.id) ? Because I try to create a simple project to render the color button by the condition, you can check it here https://stackblitz.com/edit/angular-material-button-ebwg6c?file=app/app.component.ts

CodePudding user response:

You are applying in wrong way the condition. Your condition is always true, because, 'START' always return true, since you do not compare with anything.

// false || true is always true.
job_status.get(data.id) == 'NEW' || 'START'? 'primary' : 'warn'"

Solution:

job_status.get(data.id) == 'NEW' || job_status.get(data.id) == 'START'? 'primary' : 'warn'"

// Or

"['NEW', 'START'].includes(job_status.get(data.id)) ? 'primary' : 'warn'"
  • Related