Skip to content

Commit b38bbe5

Browse files
committed
Dynamic form controls
1 parent b8a309a commit b38bbe5

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

reactive-forms/src/app/app.component.html

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,14 @@ <h2>Registration Form</h2>
2424
<small class="text-danger" *ngIf="registrationForm.errors?.misMatch">Passwords do not match</small>
2525
</div>
2626

27-
<div class="form-group">
27+
<div formArrayName="alternateEmails" class="form-group">
2828
<label>Email</label>
29+
<button class="btn btn-secondary btn-sm m-2" (click)="addAlternateEmail()">Add e-mail</button>
2930
<input type="text" [class.is-invalid]="email.invalid && email.touched" formControlName="email" class="form-control">
3031
<small class="text-danger" [class.d-none]="email.valid || email.untouched">Email is required</small>
32+
<div *ngFor="let email of alternateEmails.controls; let i=index">
33+
<input type="text" class="form-control my-1" [formControlName]="i">
34+
</div>
3135
</div>
3236

3337
<div class="form-check mb-3">

reactive-forms/src/app/app.component.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Component, OnInit } from '@angular/core';
2-
import { FormGroup, FormControl, Validators } from '@angular/forms';
2+
import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
33
import { FormBuilder } from '@angular/forms';
44
import { ForbiddenNameValidator } from './shared/user-name.validator';
55
import { PasswordValidator } from './shared/password.validator';
@@ -35,7 +35,8 @@ export class AppComponent implements OnInit {
3535
city: [''],
3636
state: [''],
3737
postalCode: ['']
38-
})
38+
}),
39+
alternateEmails: this.fb.array([])
3940
}, { validator: PasswordValidator });
4041

4142
this.registrationForm.get('subscribe').valueChanges
@@ -58,6 +59,14 @@ export class AppComponent implements OnInit {
5859
return this.registrationForm.get('email');
5960
}
6061

62+
get alternateEmails() {
63+
return this.registrationForm.get('alternateEmails') as FormArray;
64+
}
65+
66+
addAlternateEmail() {
67+
this.alternateEmails.push(this.fb.control(''));
68+
}
69+
6170
loadAPIData() {
6271
// this.registrationForm.setValue({
6372
// userName: 'Bruce',

0 commit comments

Comments
 (0)