角度反应形式,添加和删除字段?

时间:2018-03-13 21:55:09

标签: angular angular-reactive-forms

在以角度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。英语是我的第二语言,所以字段,表格等术语肯定是不正确的,希望你能明白这一点

4 个答案:

答案 0 :(得分:12)

FormGroup API公开了addControlremoveControl等方法,您可以使用这些方法在表单组初始化后添加或删除控件。

使用这些方法的示例可能如下所示:

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"> 

答案 1 :(得分:1)

首先,您可以创建选项组的模板基础。我们可以在模板中使用 * ngIf 来隐藏和显示表单中的元素组。然后,每次只传递启用的那些表单控件的对象时,使用 formBuilder 创建表单的表单实例。

  

模板

<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> 
  

角类

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));
        }

    }

答案 2 :(得分:1)

使用u的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'
  };

答案 3 :(得分:1)

这是对条件角形式控件的添加/删除操作的最简单复制。

看到您有一个名为someCheckboxControl的复选框控件的表单,请注意其布尔更改以添加/删除另一个控件。

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>