Angular 反应形式,添加和删除字段?
Angular reactive forms, adding and removing fields?
在 angular 5 中构建 crud 应用程序时,我遇到了一个问题,我如何使用相同的表单构建器,但根据我想要的、添加或更新用户来更改我获得的表单控件通过表格...
这是一些简单的代码,我会尽量不让事情复杂化,因为我有很多属性的大表单...
所以在我的 app.component.html 我有表格
<form class="form-horizontal" [formGroup]="form" #myForm="ngForm"
(ngSubmit)="save()">
<div class="form-group">
<label for="firstName" class="control-label
required">First name</label>
<input type="text" id="firstName" class="form-control"
formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName" class="control-label
required">Last name</label>
<input type="text" id="lastName" class="form-control"
formControlName="lastName">
</div>
在我的 app.component.ts
在我的构造函数中我有
this.form = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.minLength(2),
Validators.pattern(/^[a-zA-Z]+$/)]],
lastName: ['', [Validators.required, Validators.minLength(2),
Validators.pattern(/^[a-zA-Z]+$/)]],
});
和用于提交表单的 save() 函数
save() {
let formModel = this.form.value;
formModel.id = this.Id;
if (this.Id == null) {
this._usermanagementservice.addEmployee(formModel).subscribe(() => {
//function that reloads table with employees
this.LoadAllEmployees();
});
}
else {
this._usermanagementservice.updateEmployee(this.Id, formModel).subscribe(() => {
this.LoadAllEmployees();
});
}
}
注意到一切正常,我没有包含其他字段,但问题是,如何在添加用户时只包含名字字段的表单,并且只有姓氏用于更新? (为了简单起见,我在这个例子中使用名字和姓氏)
谢谢,如果您需要更多信息,我很乐意提供
Ps。英语是我的第二语言,所以字段、表单等术语肯定是不正确的,希望你能明白我的意思
FormGroup
API 公开了 addControl
和 removeControl
等方法,您可以使用这些方法在表单组初始化后向其添加或删除控件。
使用这些方法的示例可能如下所示:
formMode: 'add' | 'update';
userForm: FormGroup;
ngOnInit() {
this.form = this.formBuilder.group({
firstName: [''],
lastName: ['']
});
}
changeMode(mode: 'add' | 'update') {
if (mode === 'add') {
if (!this.form.get('firstName')) {
this.form.addControl('firstName');
}
this.form.removeControl('lastName');
} else {
if (!this.form.get('lastName')) {
this.form.addControl('lastName');
}
this.form.removeControl('firstName');
}
}
onChange(event: 'add' | 'update') {
this.changeMode(event);
}
您可能希望 DOM 根据给定控件的存在添加 *ngIf
检查来反映表单的状态:
<input *ngIf="form.get('lastName')" formControlName="lastName">
首先,您可以根据自己的选择创建一组模板。我们可以在模板中使用 *ngIf 来隐藏和显示表单中的一组元素。然后使用 formBuilder 创建表单的表单实例,每次只传递那些启用的表单控件的对象。
Template
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<label for="name">First Name:</label>
<input type="text" formControlName="fname"
placeholder="Enter name">
<br /><br />
<div *ngIf="lNameEmail1">
<label for="name">Last Name:</label>
<input type="text" formControlName="lname"
placeholder="Enter name">
<br /><br />
<label for="email">Email:</label>
<input type="email" formControlName="email"
placeholder="Enter email">
</div>
<div *ngIf="lNameEmail2">
<label for="name">Last Name2:</label>
<input type="text" formControlName="lname2"
placeholder="Enter name">
<br /><br />
<label for="email">Email2:</label>
<input type="email" formControlName="email2"
placeholder="Enter email">
</div>
<br /><br />
<button type="submit" [disabled]="!myForm.valid">Submit
</button>
<button type="submit" (click)='formGrp1()'> Form 1</button>
<button type="submit" (click)='formGrp2()'> Form 2</button>
</form>
Angular class
export class AppComponent implements AfterViewInit {
public myForm: FormGroup;
lNameEmail1 = false;
lNameEmail2 = false;
myFormProperty1 = {
"fname": new FormControl("", Validators.required)
};
myFormProperty2 = {
"fname": new FormControl("", Validators.required),
"lname": new FormControl("", Validators.required),
"email": new FormControl("")
};
myFormProperty3 = {
"fname": new FormControl("", Validators.required),
"lname2": new FormControl("", Validators.required),
"email2": new FormControl("")
};
constructor(public fb: FormBuilder) {
this.myForm = this.fb.group(this.myFormProperty1);
}
formGrp1(){
alert('Form 1 enable')
this.lNameEmail1 = true;
this.lNameEmail2 = false;
this.myForm = this.fb.group(this.myFormProperty2);
this.myForm.valueChanges.subscribe(data =>
console.log('form object ====' + JSON.stringify(data)
));
}
formGrp2(){
alert('Form 2 enable')
this.lNameEmail1 = false;
this.lNameEmail2 = true;
this.myForm = this.fb.group(this.myFormProperty3);
this.myForm.valueChanges.subscribe(data =>
console.log('form object ====' + JSON.stringify(data)
));
}
onSubmit() {
console.log('Form submitted Value=='+ JSON.stringify(this.myForm.value));
}
}
使用 addControl RemoveControl 可以隐藏和显示您的字段。
<div>
<label>Description<i class="fa fa-pencil" aria-hidden="true" (click)="editField(formControlKeys.description)"></i></label>
<h6 *ngIf="!detailForm.controls.description; else showDescriptionField">{{ projectData?.description }}</h6>
<ng-template #showDescriptionField>
<textarea formControlName="description" class="form-control" rows="2"></textarea>
<i class="fa fa-close" (click)="removeDescriptionControl()"></i>
</ng-template>
</div>
添加控件:
editField(this.formControlKeys.description){
this.detailForm.addControl('description', new FormControl(''));
this.detailForm.controls['description'].setValue(this.projectData.description);
}
删除控件:
removeDescriptionControl() {
this.detailForm.removeControl('description');
}
首先创建表单组:
this.detailForm = this.formBuilder.group({
});
设置 formControlKeys:
formControlKeys = {
description: 'description'
};
这是对条件 angular 表单控件 add/remove 最简单的复制。
看到您有一个带有名为 someCheckboxControl
的复选框控件的表单,注意它对 add/remove 另一个控件的布尔值更改。
ngOnInit() {
this.form.controls['someCheckboxControl'].valueChanges.subscribe(someCheckboxControlVal => {
if (someCheckboxControlVal) {
this.form.addControl('SomeControl', new FormControl('', Validators.required));
} else {
this.form.removeControl('SomeControl');
}
});
}
HTML
<input *ngIf="form.get('someCheckboxControl').value" formControlName="remoteLocations"</input>
在 angular 5 中构建 crud 应用程序时,我遇到了一个问题,我如何使用相同的表单构建器,但根据我想要的、添加或更新用户来更改我获得的表单控件通过表格...
这是一些简单的代码,我会尽量不让事情复杂化,因为我有很多属性的大表单...
所以在我的 app.component.html 我有表格
<form class="form-horizontal" [formGroup]="form" #myForm="ngForm"
(ngSubmit)="save()">
<div class="form-group">
<label for="firstName" class="control-label
required">First name</label>
<input type="text" id="firstName" class="form-control"
formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName" class="control-label
required">Last name</label>
<input type="text" id="lastName" class="form-control"
formControlName="lastName">
</div>
在我的 app.component.ts
在我的构造函数中我有
this.form = this.formBuilder.group({
firstName: ['', [Validators.required, Validators.minLength(2),
Validators.pattern(/^[a-zA-Z]+$/)]],
lastName: ['', [Validators.required, Validators.minLength(2),
Validators.pattern(/^[a-zA-Z]+$/)]],
});
和用于提交表单的 save() 函数
save() {
let formModel = this.form.value;
formModel.id = this.Id;
if (this.Id == null) {
this._usermanagementservice.addEmployee(formModel).subscribe(() => {
//function that reloads table with employees
this.LoadAllEmployees();
});
}
else {
this._usermanagementservice.updateEmployee(this.Id, formModel).subscribe(() => {
this.LoadAllEmployees();
});
}
}
注意到一切正常,我没有包含其他字段,但问题是,如何在添加用户时只包含名字字段的表单,并且只有姓氏用于更新? (为了简单起见,我在这个例子中使用名字和姓氏)
谢谢,如果您需要更多信息,我很乐意提供 Ps。英语是我的第二语言,所以字段、表单等术语肯定是不正确的,希望你能明白我的意思
FormGroup
API 公开了 addControl
和 removeControl
等方法,您可以使用这些方法在表单组初始化后向其添加或删除控件。
使用这些方法的示例可能如下所示:
formMode: 'add' | 'update';
userForm: FormGroup;
ngOnInit() {
this.form = this.formBuilder.group({
firstName: [''],
lastName: ['']
});
}
changeMode(mode: 'add' | 'update') {
if (mode === 'add') {
if (!this.form.get('firstName')) {
this.form.addControl('firstName');
}
this.form.removeControl('lastName');
} else {
if (!this.form.get('lastName')) {
this.form.addControl('lastName');
}
this.form.removeControl('firstName');
}
}
onChange(event: 'add' | 'update') {
this.changeMode(event);
}
您可能希望 DOM 根据给定控件的存在添加 *ngIf
检查来反映表单的状态:
<input *ngIf="form.get('lastName')" formControlName="lastName">
首先,您可以根据自己的选择创建一组模板。我们可以在模板中使用 *ngIf 来隐藏和显示表单中的一组元素。然后使用 formBuilder 创建表单的表单实例,每次只传递那些启用的表单控件的对象。
Template
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<label for="name">First Name:</label>
<input type="text" formControlName="fname"
placeholder="Enter name">
<br /><br />
<div *ngIf="lNameEmail1">
<label for="name">Last Name:</label>
<input type="text" formControlName="lname"
placeholder="Enter name">
<br /><br />
<label for="email">Email:</label>
<input type="email" formControlName="email"
placeholder="Enter email">
</div>
<div *ngIf="lNameEmail2">
<label for="name">Last Name2:</label>
<input type="text" formControlName="lname2"
placeholder="Enter name">
<br /><br />
<label for="email">Email2:</label>
<input type="email" formControlName="email2"
placeholder="Enter email">
</div>
<br /><br />
<button type="submit" [disabled]="!myForm.valid">Submit
</button>
<button type="submit" (click)='formGrp1()'> Form 1</button>
<button type="submit" (click)='formGrp2()'> Form 2</button>
</form>
Angular class
export class AppComponent implements AfterViewInit {
public myForm: FormGroup;
lNameEmail1 = false;
lNameEmail2 = false;
myFormProperty1 = {
"fname": new FormControl("", Validators.required)
};
myFormProperty2 = {
"fname": new FormControl("", Validators.required),
"lname": new FormControl("", Validators.required),
"email": new FormControl("")
};
myFormProperty3 = {
"fname": new FormControl("", Validators.required),
"lname2": new FormControl("", Validators.required),
"email2": new FormControl("")
};
constructor(public fb: FormBuilder) {
this.myForm = this.fb.group(this.myFormProperty1);
}
formGrp1(){
alert('Form 1 enable')
this.lNameEmail1 = true;
this.lNameEmail2 = false;
this.myForm = this.fb.group(this.myFormProperty2);
this.myForm.valueChanges.subscribe(data =>
console.log('form object ====' + JSON.stringify(data)
));
}
formGrp2(){
alert('Form 2 enable')
this.lNameEmail1 = false;
this.lNameEmail2 = true;
this.myForm = this.fb.group(this.myFormProperty3);
this.myForm.valueChanges.subscribe(data =>
console.log('form object ====' + JSON.stringify(data)
));
}
onSubmit() {
console.log('Form submitted Value=='+ JSON.stringify(this.myForm.value));
}
}
使用 addControl RemoveControl 可以隐藏和显示您的字段。
<div>
<label>Description<i class="fa fa-pencil" aria-hidden="true" (click)="editField(formControlKeys.description)"></i></label>
<h6 *ngIf="!detailForm.controls.description; else showDescriptionField">{{ projectData?.description }}</h6>
<ng-template #showDescriptionField>
<textarea formControlName="description" class="form-control" rows="2"></textarea>
<i class="fa fa-close" (click)="removeDescriptionControl()"></i>
</ng-template>
</div>
添加控件:
editField(this.formControlKeys.description){
this.detailForm.addControl('description', new FormControl(''));
this.detailForm.controls['description'].setValue(this.projectData.description);
}
删除控件:
removeDescriptionControl() {
this.detailForm.removeControl('description');
}
首先创建表单组:
this.detailForm = this.formBuilder.group({
});
设置 formControlKeys:
formControlKeys = {
description: 'description'
};
这是对条件 angular 表单控件 add/remove 最简单的复制。
看到您有一个带有名为 someCheckboxControl
的复选框控件的表单,注意它对 add/remove 另一个控件的布尔值更改。
ngOnInit() {
this.form.controls['someCheckboxControl'].valueChanges.subscribe(someCheckboxControlVal => {
if (someCheckboxControlVal) {
this.form.addControl('SomeControl', new FormControl('', Validators.required));
} else {
this.form.removeControl('SomeControl');
}
});
}
HTML
<input *ngIf="form.get('someCheckboxControl').value" formControlName="remoteLocations"</input>