Created
November 6, 2016 14:53
-
-
Save dherges/e1ecdd03a319fbd2a5495f54fbc1ea87 to your computer and use it in GitHub Desktop.
Angular2: reactive, nested form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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)) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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