profile.component.html
<div>
<h1>Edit Your Profile </h1>
<hr>
<div class="col-md-4">
<form [formGroup]="profileForm" (ngSubmit)="saveProfile(profileForm.value)" autocomplete="off" novalidate>
<div class="form-group">
<label for="firstName">First Name:</label>
<input formControlName="firstName" id="firstName" type="text" class="form-control" placeholder="First Name..." />
</div>
<div class="form-group">
<label for="lastName">Last Name:</label>
<input formControlName="lastName" id="lastName" type="text" class="form-control" placeholder="Last Name..." />
</div>
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" (click)="cancel()">Cancel</button>
</form>
</div>
</div>
profile.component.ts
import { AuthService } from './auth.service';
import { Component, OnInit } from '@angular/core'
import { FormControl, FormGroup } from '@angular/forms'
import { Router } from '@angular/router';
@Component({
templateUrl: './profile.component.html',
})
export class ProfileComponent implements OnInit{
profileForm: FormGroup
constructor(private authService: AuthService, private router: Router){}
ngOnInit(){
let firstName = new FormControl(this.authService.currentUser.firstName)
let lastName = new FormControl(this.authService.currentUser.lastName)
this.profileForm = new FormGroup({
firstName: firstName,
lastName: lastName
})
}
cancel(){
this.router.navigate(['events'])
}
saveProfile(formValues){
this.authService.updateCurrentUser(formValues.firstName, formValues.lastName)
}
}
auth.service.ts
import { Injectable } from '@angular/core';
import { IUser } from './user.model';
@Injectable()
export class AuthService{
currentUser: IUser;
//debugger;
loginUser(userName: string, password: string){
this.currentUser = {
id: 1,
userName: userName,
firstName: 'Bipon',
lastName: 'Biswas'
}
}
isAuthenticated(){
return !this.currentUser;
}
updateCurrentUser(firstName:string, lastName: string){
this.currentUser.firstName = firstName
this.currentUser.lastName = lastName
}
}
app.module.ts
import { ProfileComponent } from './profile.component';
import { NgModule } from '@angular/core'
import { CommonModule } from '@angular/common'
import { RouterModule } from '@angular/router'
import { userRoutes } from './user.routes'
import { LoginComponent } from './login.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
RouterModule.forChild(userRoutes)
],
declarations: [
ProfileComponent,
LoginComponent
],
providers: [
]
})
export class UserModule{
}