Skip to content

Instantly share code, notes, and snippets.

@AmauryLugdu
Created December 2, 2019 20:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AmauryLugdu/5bd8bf5c1109af690d02f9a84998497d to your computer and use it in GitHub Desktop.
Save AmauryLugdu/5bd8bf5c1109af690d02f9a84998497d to your computer and use it in GitHub Desktop.
15 - Angular - Les formulaires : Reactive Form et FormGroup
<form [formGroup]= "userForm"(ngSubmit)="onSubmit()">
<div formGroupName="address">
<div>
<label>
Street:
<input type="text" formControlName="street">
</label>
</div>
<div>
<label>
City:
<input type="text" formControlName="city">
</label>
</div>
<div>
<label>
Zip:
<input type="text" formControlName="zip">
</label>
</div>
</div>
<div>
<label>
Username:
<input type="text" formControlName="username">
</label>
</div>
<div formGroupName="credentials">
<div>
<label>
Email:
<input type="text" formControlName="mail">
</label>
</div>
<div>
<label>
Password:
<input type="text" formControlName="password">
</label>
</div>
</div>
<button type="submit" [disabled]="!userForm.valid">Submit</button>
</form>
<div *ngFor = "let user of users">
{{user.username}}
{{user.credentials.mail}}
{{user.credentials.password}}
{{user.address.street}}
{{user.address.city}}
{{user.address.zip}}
</div>
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, FormBuilder } from '@angular/forms';
import { User } from 'src/User';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
newUser: User = new User;
users : User [] = [];
userForm = this.fb.group({
username: [''],
credentials: this.fb.group({
mail: [''],
password: ['']
}),
address: this.fb.group({
street: [''],
city: [''],
zip: ['']
})
});
onSubmit() {
this.users.push(this.userForm.value);
console.log(this.users)
}
constructor(private fb: FormBuilder) { }
ngOnInit() {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment