Angular reactive forms, adding and removing fields?

前端 未结 4 884
孤街浪徒
孤街浪徒 2021-02-14 10:27

while building crud app in angular 5 I\'ve come across with a question, how can I use the same form builder but change what form controls I get depending on what I want, adding

相关标签:
4条回答
  • 2021-02-14 11:02

    First you can create group of template basis of your option. We can use *ngIf in template to hide and show group of elements in form. Then use formBuilder to create form instance of form each time pass only object of those form controls which are enable.

    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));
            }
    
        }
    
    0 讨论(0)
  • 2021-02-14 11:08

    The FormGroup API exposes methods such as addControl and removeControl which you can use to add or remove controls from your form group after it has been initialized.

    An example using these methods might look like:

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

    You'll probably want your DOM to reflect the state of your form by adding *ngIf checks based on the existence of a given control:

    <input *ngIf="form.get('lastName')" formControlName="lastName"> 
    
    0 讨论(0)
  • 2021-02-14 11:11

    addControl RemoveControl using u can hide and show your Fields.

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

    Add control:

    editField(this.formControlKeys.description){
            this.detailForm.addControl('description', new FormControl(''));
            this.detailForm.controls['description'].setValue(this.projectData.description);
    }
    

    remove control:

     removeDescriptionControl() {
        this.detailForm.removeControl('description');
      }
    

    create form group first:

     this.detailForm = this.formBuilder.group({
        });
    

    set formControlKeys:

    formControlKeys = {
        description: 'description'
      };
    
    0 讨论(0)
  • 2021-02-14 11:14

    This is the most simple replication of add/remove for conditional angular form controls.

    Seeing that you have a form with a checkbox control named someCheckboxControl watch for its boolean changes to add/remove the other control.

    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>
    
    0 讨论(0)
提交回复
热议问题