Created
December 2, 2019 20:30
-
-
Save AmauryLugdu/5bd8bf5c1109af690d02f9a84998497d to your computer and use it in GitHub Desktop.
15 - Angular - Les formulaires : Reactive Form et FormGroup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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