簡體   English   中英

Angular的setter和getter

[英]setter and getter for Angular

在angular中,有一個內置的動作對話框框架,當showDialog = true時,我必須使用該框架來顯示動作彈出窗口。

當showDialog = true時將顯示操作對話框,否則在showDialog = false時將隱藏操作對話框

當showDialog = false時,必須使用setter和getter方法來調用cancel方法。

但是,在調試代碼時,即使我沒有觸發動作對話框,它也會繼續檢查getter和setter方法。

有沒有一種方法可以在Angular中使用生命周期方法比較showDialog的先前值和當前布爾值。 示例:如果previousValue.showDialog!= currentValue.showDialog,則僅調用get showDialog(),設置showDialog()和cancel()。

我正在考慮在Angular中使用某些生命周期方法,例如ngAfterViewInit()。 您知道如何存儲showDialog的以前的布爾值,以便可以與showDialog的當前值進行比較。

在React中,我可以使用具有prev props值的getDerivedStateFromProps,但是您知道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
    });
}

您可以使用ngOnChanges生命周期掛鈎。 此生命周期掛鈎獲取類型為simpleChanges的變量,並且其中一個值是先前值。

@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() { }
}

這是從父組件調用此組件的方式:

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

這將是控制台:

測試:SimpleChange,currentValue:“ 2”,firstChange:true,previousValue:未定義

這樣就可以知道當前值,先前值,即使這是第一次更改也是如此

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM