add and remove text input element dynamically any one can use this this will work Type of Contact Balance Fund Equity Fund Allocation Allocation % is required! Remove Add Contact
userForm: FormGroup;
public contactList: FormArray;
// returns all form groups under contacts
get contactFormGroup() {
return this.userForm.get('funds') as FormArray;
}
ngOnInit() {
this.submitUser();
}
constructor(public fb: FormBuilder,private router: Router,private ngZone: NgZone,private userApi: ApiService) { }
// contact formgroup
createContact(): FormGroup {
return this.fb.group({
fundName: ['', Validators.compose([Validators.required])], // i.e Email, Phone
allocation: [null, Validators.compose([Validators.required])]
});
}
// triggered to change validation of value field type
changedFieldType(index) {
let validators = null;
validators = Validators.compose([
Validators.required,
Validators.pattern(new RegExp('^\\+[0-9]?()[0-9](\\d[0-9]{9})$')) // pattern for validating international phone number
]);
this.getContactsFormGroup(index).controls['allocation'].setValidators(
validators
);
this.getContactsFormGroup(index).controls['allocation'].updateValueAndValidity();
}
// get the formgroup under contacts form array
getContactsFormGroup(index): FormGroup {
// this.contactList = this.form.get('contacts') as FormArray;
const formGroup = this.contactList.controls[index] as FormGroup;
return formGroup;
}
submitUser() {
this.userForm = this.fb.group({
first_name: ['', [Validators.required]],
last_name: [''],
email: ['', [Validators.required]],
company_name: ['', [Validators.required]],
license_start_date: ['', [Validators.required]],
license_end_date: ['', [Validators.required]],
gender: ['Male'],
funds: this.fb.array([this.createContact()])
})
this.contactList = this.userForm.get('funds') as FormArray;
}
addContact() {
this.contactList.push(this.createContact());
}
removeContact(index) {
this.contactList.removeAt(index);
}