要仅获取已填写的控件,你可以使用Angular的FormControl的valueChanges属性来监听表单控件的值变化,并根据值是否为空来判断是否已填写。
以下是一个示例代码:
在组件类中定义一个表单控件的集合:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
name: new FormControl(''),
email: new FormControl(''),
password: new FormControl('')
});
}
getFilledControls() {
const filledControls = {};
Object.keys(this.form.controls).forEach(key => {
const control = this.form.controls[key];
if (control.value !== '') {
filledControls[key] = control.value;
}
});
console.log(filledControls);
}
}
在模板中使用表单控件和添加一个按钮来获取已填写的控件:
在点击获取按钮时,调用getFilledControls()方法来获取已填写的控件的值。这个方法会遍历所有的控件,如果控件的值不为空,就将其添加到一个对象中,并打印出来。
希望这可以帮助到你!