尝试在Angular中向formGroup动态添加一个新的formControl条目。
method() {
this.testForm.addControl('new', ('', Validators.required));
}
可以这样做吗?
答案 0 :(得分:69)
当然,但第二个参数应该是FormControl实例。类似的东西:
this.testForm.addControl('new', new FormControl('', Validators.required));
如果您想使用' setValidators'还可以动态添加验证器。方法
答案 1 :(得分:10)
如果您在表单中使用import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(QtWidgets.QMainWindow):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(346, 182)
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setGeometry(QtCore.QRect(110, 80, 75, 23))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(Dialog.close) # <---
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
_translate = QtCore.QCoreApplication.translate
Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
self.pushButton.setText(_translate("Dialog", "OK"))
,也可以使用它来添加控件:
FormBuilder
答案 2 :(得分:2)
简单使用:
this.testForm.addControl('new', this.fb.group({
name: ['', Validators.required]
}));
答案 3 :(得分:1)
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-component-name',
templateUrl: './component-name.component.html',
styleUrls: ['./component-name.component.scss']
})
export class ComponentName implements OnInit {
formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.formGroup = this.formBuilder.group({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
});
}
// Add single or multiple controls here
addNewControls(): void {
this.formGroup = this.formBuilder.group({
...this.formGroup.controls,
email: ['', Validators.required],
phone: ['', Validators.required]
});
}
}