15

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

4 Answers 4

37

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"> 
Sign up to request clarification or add additional context in comments.

3 Comments

I found this question because I didn't understand how to use formControlName if addControl is being used to adjust the inputs dynamically. My inputs were hidden, but it was still causing issues. Thank you for your suggestion to use *ngIf.
Just a thought! Calling this.form.updateValueAndValidity() is enough to update the DOM right?
Plz help I have some fields that only display if other fields are set to specific values... I need to remove no longer visible fields with removeControl(), but doing so is removing custom error messages from other fields!
6

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>

Comments

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

Comments

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

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.