angular - 将以前的值与输出发射器和 ValueChanges 进行比较

标签 angular typescript angular8 angular-reactive-forms

我们有一个 Angular 子表单,通过 Valuechanges 发出值。在父组件中,如果子组件的新邮政编码值与以前的邮政编码值不同,我们希望运行任务。

现在,我们正在创建一个变量来存储以前的邮政编码。

有没有更简洁的方法来使用输出来执行此操作? 我知道输入的 NgOnchanges,我们可以使用changes.previousValue 跟踪之前的更改。

好奇输出值变化是否有类似的情况?

子表单:

public addressSub = new Subscription();
public editAddressForm: FormGroup;
@Output addressFormChange = new EventEmitter<any>();

this.addressSub.add(this.editAddressForm.valueChanges.subscribe(data=> {
    this.addressFormChange.emit(this.editAddressForm);
})))

父组件:

在父级中,它是订阅的。

public addressFormChangeEvent(addressFormEvent){
    this.addressMailingForm = addressFormEvent;
    if (this.addressMailingForm.get('zipCode') != previousZipCode) {
         doSomethingetc();
    }
    previousZipCode = this.addressMailingForm.get('zipCode');
}

Angular 库中是否有一些东西可以通过 ValueChanges 订阅查看以前的值?

最佳答案

IMO 更简单的方法是在 pairwise 的帮助下完成此操作。和 startWith .
另外,您可以将表单从父组件传递给子组件并在父组件中订阅,例如:

form.valueChanges
    .pipe(startWith(undefined), pairwise())
    .subscribe(valuesArray => {
         const newVal = valuesArray[1];
         const oldVal = valuesArray[0];
         if (newVal !== oldVal) {
             // do your thing
         }
    })

关于angular - 将以前的值与输出发射器和 ValueChanges 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60622963/

相关文章:

angular - 如何将两个对象数据合并为一个

angular - 无法绑定(bind)到 'ngModel',因为它不是 'input' 的已知属性。测试.spec.ts

typescript - 当 '--module' 为 'none' 时,Visual Studio 2019 无法使用导入、导出或模块扩充

angular - 我在实现 ngx-Spinner 8.0.3 时遇到错误

javascript - Angular 插值滞后于渲染某些值以及如何从 typescript 对象数组中删除一项

angular - Primeng修复按钮大小

html - Bootstrap 3 : two button on a row

angular - 未处理的 promise 拒绝 : No provider for HTTPService

angular - 从 Angular 8 的下拉列表中删除/禁用选定的选项(动态创建的)

node.js - TS1086 : An accessor cannot be declared in ambient context in Angular 8 application using docker-compose