Thursday, April 26, 2018

How do I nest some of the controls inside of an Angular 4 reactive form in their own components?

Let's say our nested component looks like so:

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
   selector: 'joy',
   templateUrl: './joy.component.html'
})
export class JoyComponent {
   @Input() MyGroup: FormGroup;
}

 
 

Let's give it an amazingly simple template.

<ng-container [formGroup]="MyGroup">
   <input formControlName='yang' />
</ng-container>

 
 

Fine. Now how may we drag it into some sort of bigger picture?

import { Component } from '@angular/core';
import { NgForm, FormGroup, FormArray, FormControl } from '@angular/forms';
@Component({
   selector: 'front-door',
   templateUrl: './layout.component.html',
   styleUrls: ['./layout.component.css']
})
export class LayoutComponent {
   whateverForm:FormGroup;
   
   ngOnInit() {
      let first = new FormGroup({
         'yin': new FormControl("13"),
         'yang': new FormControl("23")
      });
      let second = new FormGroup({
         'yin': new FormControl("27"),
         'yang': new FormControl("42")
      });
      let third = new FormGroup({
         'yin': new FormControl("69"),
         'yang': new FormControl("86")
      });
      this.whateverForm = new FormGroup({
         'lineItems': new FormArray([first, second, third])
      });
   }
   
   constructor() { }
   
   whatever(x: NgForm) {
      console.log(x);
   }
}

 
 

The component above and its template below show off crosstalk with the JoyComponent. If you change a value at the form field inside the JoyComponent and press the button the dirty flag for the whole of the form will get logged as true because a form field was affirmed as changed.

<form [formGroup]="whateverForm" (ngSubmit)="whatever(x)" #x="ngForm">
   <table formArrayName="lineItems">
      <tr *ngFor="let lineItem of whateverForm.get('lineItems').controls; let i=index"
            [formGroupName]="i">
         <td>
            <input type="text" formControlName="yin" />
         </td>
         <td>
            <joy [MyGroup]="lineItem"></joy>
         </td>
      </tr>
   </table>
   <input type="submit" />
</form>

 
 

It's not that tricky.

No comments:

Post a Comment