Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular reactive forms, adding and removing fields?

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

like image 758
Questions Avatar asked Mar 13 '18 21:03

Questions


People also ask

How do you set a validator dynamically?

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.


2 Answers

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"> 
like image 164
vince Avatar answered Oct 20 '22 01:10

vince


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>
like image 35
Ben Racicot Avatar answered Oct 19 '22 23:10

Ben Racicot