Skip to content

Instantly share code, notes, and snippets.

@Oleg-Sulzhenko
Last active May 22, 2019 12:56
Show Gist options
  • Save Oleg-Sulzhenko/fb1405a2ca2ad17817b67ea3e4da4f85 to your computer and use it in GitHub Desktop.
Save Oleg-Sulzhenko/fb1405a2ca2ad17817b67ea3e4da4f85 to your computer and use it in GitHub Desktop.
import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
constructor(
private fb: FormBuilder
) {
this.complexForm = fb.group({
firstName : [null, Validators.required],
lastName: [null, Validators.compose([Validators.required, Validators.minLength(5), Validators.maxLength(10)])],
gender: ['Female'],
hiking : false,
daysOfMonth: this.fb.array([]),
});
this.complexForm.get('SOME_FIELD').valueChanges.subscribe( (filed: any) => {
console.log('form.SOME_FIELD changed to:', filed);
});
this.complexForm.valueChanges.subscribe( (form: any) => {
console.log('form changed to:', form);
});
}
setValueOfForm() {
this.complexForm.setValue({
...this.complexForm.value,
firstName: 'value',
});
}
// Function to clear fb.array -> [];
// this.clearFormArray(this.complexForm.get('FORM_ARRAY_FIELD_NAME') as FormArray);
public clearFormArray(formArray: FormArray) {
while (formArray.length !== 0) {
formArray.removeAt(0);
}
}
// Add/Delete value from/to FormArray
public onCheckbox(event: any, formFiledName: string) {
const formFiled = <FormArray>this.complexForm.get(formFiledName) as FormArray;
if (event.checked) {
formFiled.push(new FormControl(event.source.value));
} else {
const i = formFiled.controls.findIndex(x => x.value === event.source.value);
formFiled.removeAt(i);
}
}
========================================================================================
// HTML Template
<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
<div class="form-group">
<label>First Name:</label>
<input class="form-control" type="text" placeholder="John" [formControl]="complexForm.controls['firstName']">
</div>
<div class="form-group">
<label>Last Name</label>
<input class="form-control" type="text" placeholder="Doe" [formControl]="complexForm.controls['lastName']">
</div>
<div class="form-group">
<label>Gender</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="Male" [formControl]="complexForm.controls['gender']">
Male
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="gender" value="Female" [formControl]="complexForm.controls['gender']">
Female
</label>
</div>
<div class="form-group">
<label>Activities</label>
</div>
<label class="checkbox-inline">
<input type="checkbox" value="hiking" name="hiking" (change)="onCheckbox($event, 'hiking')" [formControl]="complexForm.controls['hiking']"> Hiking
</label>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment