简体   繁体   中英

setter and getter for Angular

In angular, there is a built in action dialog framework which I've to use to display the action pop up window when showDialog = true.

The action dialog will be shown when showDialog=true, else the action dialog will hide when showDialog=false

Have to use the setter and getter method to call cancel method when showDialog = false.

However when debugging the code, it keeps on checking the getter and setter method even though I've not trigger the action dialog.

Is there a way that I could use lifecycle method in Angular to compare the previous value and current boolean value of showDialog. Example: if previousValue.showDialog != currentValue.showDialog, then only call get showDialog(), set showDialog(), and cancel().

i was thinking of using some lifecycle method in Angular like ngAfterViewInit(). Do you know how do I store previous boolean val of showDialog, so that I can compare to the current val of showDialog.

In React, I could use getDerivedStateFromProps which has the prev props value but do you know if there is similar method in Angular.

a.html

   <action-dialog [(openDialog)]="showDialog"/>

b.html

      <button (click)="showDialog = true">
                    {{intl.cleanNow | uppercase}}
      </button>

a.ts

  get showDialog() {
      return this._showDialog;
   }

  set showDialog(val){
    if (val === false) {
        this.cancel();
    } else if (val === true) {
        this._showDialog = true;
    }
}

 cancel() { 
    this.showDialog = false;
    this.form.reset({
        throttle: this._originalThrottle || 50
    });
}

You can use the ngOnChanges life cycle hook. This life cycle hook gets an variable of type simpleChanges and one of it value is previous value.

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit, OnChanges {
  @Input() test: string;
  constructor() { }

  ngOnChanges(changes: SimpleChanges) {
    console.log(changes);
  }

  ngOnInit() { }
}

This is how you call this component from parent component:

<app-test [test]="'2'"></app-test>

This will be the console:

test: SimpleChange, currentValue: "2", firstChange: true, previousValue: undefined

So you can know the current value, the previous value and even if this was the first change or not

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM