繁体   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