Skip to content

Instantly share code, notes, and snippets.

@dherges
Created November 6, 2016 14:53
Show Gist options
  • Save dherges/e1ecdd03a319fbd2a5495f54fbc1ea87 to your computer and use it in GitHub Desktop.
Save dherges/e1ecdd03a319fbd2a5495f54fbc1ea87 to your computer and use it in GitHub Desktop.
Angular2: reactive, nested form
@Component({
selector: 'items-array',
template:
`
<fieldset>
<h6>Items</h6>
<div *ngIf="itemsFormArray.hasError('minSum')">
You must buy a total sum of at least {{ itemsFormArray.getError('minSum') }}.
</div>
<item-control
*ngFor="let item of itemsFormArray.controls; let i=index"
[index]="i" [item]="item" (removed)="itemsFormArray.removeAt($event)">
</item-control>
</fieldset>
<button type="button" class="btn btn-link" (click)="addItem()">Add another item</button>
`,
styles: [':host {display:block;}']
})
export class ItemsFormArrayComponent {
@Input()
public itemsFormArray: FormArray;
addItem() {
this.itemsFormArray.push(ItemFormControlComponent.buildItem(''))
}
static buildItems() {
return new FormArray([
ItemFormControlComponent.buildItem('aaa'),
ItemFormControlComponent.buildItem('')],
ItemsValidators.minQuantitySum(300))
}
}
@Component({
selector: 'nested-form',
template:
`
<form [formGroup]="myForm" (ngSubmit)="submit()">
<items-array
formArrayName="items"
[itemsFormArray]="myForm.get('items')">
</items-array>
</form>
`
})
export class NestedFormComponent implements OnInit {
myForm: FormGroup;
constructor(
private fb: FormBuilder
) {}
ngOnInit() {
this.myForm = this.fb.group({
items: ItemsFormArrayComponent.buildItems()
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment