typescript 角反应形式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 角反应形式相关的知识,希望对你有一定的参考价值。
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>
以上是关于typescript 角反应形式的主要内容,如果未能解决你的问题,请参考以下文章