Home > Net >  Enable mat button only on object change
Enable mat button only on object change

Time:02-12

I have a mat-toggle-button which I would like to make clickable only when an object in the ts class is changed, otherwise it should stay greyed out

<mat-button-toggle (click)="updateChanges()" appearance="fill">Update changes</mat-button-toggle>

I thought of using the SimpleChanges API for this as it tracks status changes on a registered object (ideal for my case).

@Input() myObject: MyObject;
public updateButtonClickable: boolean = false;
 ngOnChanges(changes: SimpleChanges) {
        if (changes.myObject) {
            this.updateButtonClickable = true;
        } else {
            this.updateButtonClickable = false;
        }
    }

The first problem is that this approach detects changes at page loading, so my boolean flag variable will be set to true when the page loads, annoying as i would not define this a status change.
Now my second issue is to bind the button status to this variable value, i have been looking at the material page but i dont see the way how I could achive this, any idea?

CodePudding user response:

We could compare if we have previousValue. And if previousValue is not the same as currentValue then it must be a new obj. We use [disabled] to "gray out" and make the button not clickable if updateButtonClickable boolean is false.

@Component({
  selector: 'hello',
  template: `<p>Complex: {{ complex | json }}</p><br>
  <button [disabled]="!updateButtonClickable">I am button</button>
  <br>
  <br>`,
})
export class HelloComponent implements OnChanges {
  @Input() myObject: any;
  public updateButtonClickable: boolean = false;

  ngOnChanges(changes: SimpleChanges) {
    if (changes.myObject) {
      console.log(changes);
      if (
        changes.myObject.previousValue != undefined &&
        changes.myObject.previousValue != changes.myObject.currentValue
      ) {
        console.log('yes now enable');
        this.updateButtonClickable = true;
      } else {
        this.updateButtonClickable = false;
      }
    }
  }
}

Here is a working example: https://stackblitz.com/edit/angular-ng-on-changes-example-v44p6v?file=src/app/hello.component.ts

  • Related