I am trying to update a row in database by passed ID.
I am having a form component, as you can see I am using reactive formBuilder:
@Component({
selector: 'program-form',
templateUrl: './program.form.component.html',
styleUrls: ['./program.form.component.css']
})
export class ProgramFormComponent implements OnInit {
form: FormGroup;
title: string;
program: ProgramModel = new ProgramModel();
constructor(
formBuilder: FormBuilder,
private router: Router,
private route: ActivatedRoute,
private dataService: DataService
) {
this.form = formBuilder.group({
name: ['', [
Validators.required,
Validators.minLength(3)
]],
// email: ['', [
// Validators.required,
// BasicValidators.email
// ]],
// phone: [],
// address: formBuilder.group({
// street: ['', Validators.minLength(3)],
// suite: [],
// city: ['', Validators.maxLength(30)],
// zipcode: ['', Validators.pattern('^([0-9]){5}([-])([0-9]){4}$')]
// })
});
}
ngOnInit() {
var id = this.route.params.subscribe(params => {
var id = params['id'];
this.title = id ? 'Edit' : 'New';
if (!id)
return;
this.getProgram(id);
});
}
private getProgram(id: number) {
this.dataService.setEndpoint('/api/program/getsingle');
this.dataService
.GetSingle(id)
.subscribe(data => {
this.program = data
}, (error) => {
console.log(error);
});
}
create() {
var result,
userValue = this.form.value;
console.log(userValue.Id + ", userValueId");
if (userValue.id){
this.dataService.setEndpoint('/api/program/update');
result = this.dataService.Update(userValue.Id, userValue);
}
else
{
this.dataService.setEndpoint('/api/program/create');
this.dataService.Create(userValue).subscribe(data => {
(data => this.router.navigate(['users']));
}, (error) => {
console.log(error);
});;
}
//result.subscribe(data => this.router.navigate(['users']));
}
}
Html:
<div class="row">
<form materialize class="col s12" [formGroup]="form" (ngSubmit)="create()">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">account_circle</i>
<label for="name"
[class.active]="program.name"
data-error="Name is required and needs to contain at least 3 chars">
Name
</label>
<input id="name" type="text" class="validate"
[(ngModel)]="program.name" formControlName="name"
[class.invalid]="form.controls['name'].touched && !form.controls['name'].valid">
</div>
</div>
<button class="btn waves-effect waves-light" type="submit">
Submit<i class="material-icons right">send</i>
</button>
</form>
</div>
How do I retrieve ID from this.form.value as you can see I am trying to get id, but console.log says it's undefined. Do I have to initialize it inside of form builder or inside of html?