Angular reactive forms, adding and removing fields?

五迷三道 提交于 2020-01-22 19:54:09

问题


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 or updating users thru form...

Here's some simple code, I will try not to complicate things, since I have pretty big form with lot of attributes...

So in my app.component.html i have form

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

and in my app.component.ts

in my constructor i have

    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]+$/)]],

    });

and save() function for submiting the form

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

Noted that everything works, I've not included other fields, but here's the question, how can I include only form for first name field on adding user, and have ONLY last name for updating? (to simplfy things, I'm using this example first and last name)

Thanks, If you need more info, I'll gladly provide it Ps. english is my secondary language, so terms like fields, forms and etc. are for sure incorrect, hopefully you'll get the point


回答1:


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

    }



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/49266469/angular-reactive-forms-adding-and-removing-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!