I need a list of urls in a form. A repeaterfield. Something like this:
Im using a FormGroup which I initialise like this:
this.myForm = this.fb.group({
otherField: ['', Validators.required],
urls: this.fb.array([
new FormControl('test'),
new FormControl('test2')
]),
.
.
.
});
Some getter methods:
private get urls() { return this.myForm .get('urls'); }
private get otherField() { return this.myForm .get('otherField'); }
On the HTML-Side it looks like this:
<form [formGroup]="myForm">
<div class="form-row">
<div class="col mb-3">
<input type="text" class="form-control" formControlName="otherField">
</div>
</div>
<div class="form-row">
<div class="col mb-3" formArrayName="urls">
<div class="input-group" *ngFor="let item of urls.controls; let i = index" >
<input type="text" class="form-control" formControlName="???">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button">
<i class="fas fa-plus"></i>
</button>
</div>
</div>
</div>
</div>
</form>
This already displays the right amount of inputs (two in this minimal example). But how do I bind the date to the input? What can I use as formControllName?
(Assuming urls2
is a typo)
Since we are dealing with single formcontrols, we can use the index value of the iteration to refer to the form controls, so just add [formControlName]="i"
for your inputs:
<div class="col mb-3" formArrayName="urls">
<div class="input-group" *ngFor="let item of urls.controls; let i = index" >
<input type="text" class="form-control" [formControlName]="i">
</div>
</div>