I'm trying to add input fields dynamically while the user clicks the add button and for each form field there must be a remove button, when the user clicks that the form fields must be removed, I need to achieve this using Angular 2, as I'm new to Angular 2 please help me to complete it
What I have tried
I have created a set of fields (3 select box and 1 text box), created a button called add fields, but I have tried it in angular 1.x its working fine but in angular 2 I don't know how to complete it, this is link of my full work
app/app.component.ts
import {
Component
}
from '@angular/core';
@Component({
selector: 'my-app',
template: `
<h1>{{title}}</h1>
<div class="container">
<button class="btn btn-success bt-sm">add</button>
<form role="form" calss="form-inline">
<div class="form-group col-xs-3">
<label>Select State:</label>
<select class="form-control" [(ngModel)]="rules.State" id="sel1">
<option>State1</option>
<option>State2</option>
<option>State3</option>
<option>State4</option>
</select>
</div>
<div class="form-group col-xs-3">
<label>Rule:</label>
<input type="text" data-toggle="modal" data-target="#myModal" class="form- control">
</div>
<div class="form-group col-xs-3">
<label>Pass State :</label>
<select class="form-control" [(ngModel)]="rules.pass">
<option>State1</option>
<option>State2</option>
<option>State3</option>
<option>State4</option>
</select>
</div>
<div class="form-group col-xs-3">
<label>Fail State:</label>
<select class="form-control" [(ngModel)]="rules.fail">
<option>State1</option>
<option>State2</option>
<option>State3</option>
<option>State4</option>
</select>
</div>
</form>
</div>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">× </button>
<h4 class="modal-title">Rules Configuration</h4>
</div>
<div class="modal-body">
<p>Rules</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data- dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
`
})
export class AppComponent {
title = 'Rule Engine Demo';
rules: Rules = {
State: '',
pass: '',
fail: ''
};
This question is related to
angular
addAccordian(type, data) { console.log(type, data);
let form = this.form;
if (!form.controls[type]) {
let ownerAccordian = new FormArray([]);
const group = new FormGroup({});
ownerAccordian.push(
this.applicationService.createControlWithGroup(data, group)
);
form.controls[type] = ownerAccordian;
} else {
const group = new FormGroup({});
(<FormArray>form.get(type)).push(
this.applicationService.createControlWithGroup(data, group)
);
}
console.log(this.form);
}
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);
}
That is the HTML code. Anyone can use this:
<div class="card-header">Contact Information</div>
<div class="card-body" formArrayName="funds">
<div class="row">
<div class="col-6" *ngFor="let contact of contactFormGroup.controls; let i = index;">
<div [formGroupName]="i" class="row">
<div class="form-group col-6">
<label>Type of Contact</label>
<select class="form-control" formControlName="fundName" type="text">
<option value="01">Balance Fund</option>
<option value="02">Equity Fund</option>
</select>
</div>
<div class="form-group col-12">
<label>Allocation</label>
<input class="form-control" formControlName="allocation" type="number">
<span class="text-danger" *ngIf="getContactsFormGroup(i).controls['allocation'].touched &&
getContactsFormGroup(i).controls['allocation'].hasError('required')">
Allocation % is required! </span>
</div>
<div class="form-group col-12 text-right">
<button class="btn btn-danger" type="button" (click)="removeContact(i)"> Remove </button>
</div>
</div>
</div>
</div>
</div>
<button class="btn btn-primary m-1" type="button" (click)="addContact()"> Add Contact </button>
Source: Stackoverflow.com