gpt4 book ai didi

Angular Reactive Form Programmatic Setter

转载 作者:行者123 更新时间:2023-12-04 02:02:30 25 4
gpt4 key购买 nike

我有一个 Angular Reactive Form与验证。为我的 hiddenComposedField 调用 setter 的正确方法是什么?

组件.ts

ngOnInit() {
this.myForm = this.formBuilder.group({
'field1': ['', [Validators.required]],
'field2': ['', [Validators.required]],
'hiddenComposedField': [''],
});

this.myForm.get('field1').valueChanges.subscribe((val) => {
this.setHiddenComposedField();
});
this.myForm.get('field2').valueChanges.subscribe((val) => {
this.setHiddenComposedField();
});
}

setHiddenComposedField() {
let field1 = this.myForm.get('field1').value;
let field2 = this.myForm.get('field2').value;

// This doesn't work, but I want something like it:
this.myForm.set('hiddenComposedField',field1 + ' ' + field2); // :(
}

组件.html

<form [formGroup]="myForm">
<input formControlName="field1">
<input formControlName="field2">
<!-- NB: hiddenComposedField is not exposed to the user; -->
<!-- it is only on the submitted form model. -->
<button type="submit">Submit</button>
</form>

最佳答案

这样的事情应该会起作用,这样您就可以先获取控件,然后再设置它的值。

this.myForm.get('hiddenComposedField').setValue(field1 + ' ' + field2);

关于Angular Reactive Form Programmatic Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46185457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com