hel*_* rb 5 angular angular-reactive-forms
我尝试使用反应式表单,我只需要为每个填充的项目创建键但是因为创建的第一个时刻,如果字段未满,它会发送 null 而我想要一个不为空的字段我发送的所有代码是:
form: FormGroup;
constructor() {
this.form = new FormGroup({
basePrice: new FormControl(null, [customeValidator.numberOnly()]),
discountValue: new FormControl(null, [customeValidator.numberOnly()]),
roomViewCount: new FormControl(null, [customeValidator.numberOnly()])
});
}
onCalcute() {
console.log(this.form.value);
if (this.form.valid) {
this.roomData = {
basePrice: this.form.value.basePrice,
discountValue: this.form.value.discountValue,
roomViewCount: this.form.value.roomViewCount
};
this.clicked = true;
}
}
Run Code Online (Sandbox Code Playgroud)
如果其中只有一个已满 console.log 返回
{
basePrice: 20,
discountValue: null,
roomViewCount: null
}
Run Code Online (Sandbox Code Playgroud)
但是我需要:
{
basePrice: 20
}
Run Code Online (Sandbox Code Playgroud)
您可以在提交函数中过滤空值:
onSubmit() {
const filtered = {};
if (this.form.valid) {
for (let key in this.form.value) {
if (this.form.value[key]) {
filtered[key] = this.form.value[key];
}
}
console.log(filtered);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3215 次 |
| 最近记录: |