Hey there, I'm struggling to submit a form with just one field using Angular 7. However, I keep encountering this error specifically on the Input line:
ERROR TypeError: Cannot read property 'Name' of undefined
This is how my HTML code looks like:
<form #form="ngForm" autocomplete="off" (submit)="onSubmit(form)">
<input type="hidden" name="Id" [value]="service.formData.Id">
<div class="form-group" >
<div class="input-group" *ngIf="service">
<div class="input-group-prepend">
<div class="input-group-text bg.white">
<i class="fas fa-user" [class.green-icon]="Name.valid" [class.red-icon]="Name.invalid && Name.touched"></i>
</div>
</div>
<input name="Name" #Name="ngModel" [(ngModel)]="service.formData.Name" class="form-control" placeholder="Student Name" required maxlength="50">
</div>
</div>
<hr>
<div class="form-group">
<button class="btn btn-success btn-lg btn-block" type="submit"><i class="fas fa-database"></i> Submit</button>
</div>
</form>
Here is my component setup:
import { Component, OnInit } from '@angular/core';
import { StudentDetailService } from 'src/app/shared/student-detail.service';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-student-detail',
templateUrl: './student-detail.component.html',
styles: []
})
export class StudentDetailComponent implements OnInit {
constructor(private service:StudentDetailService) { }
ngOnInit() {
this.resetForm();
}
resetForm(form?:NgForm)
{
if(form !=null){
form.resetForm();
this.service.formData = {
Id :0,
Name :'',
StudentSubjects :null
}
}
}
onSubmit(form:NgForm)
{
this.service.postStudentDetail(form.value).subscribe(
res => {
this.resetForm(form);
},
err => {
console.log(err)
}
);
}
}
And here's my Service implementation:
import { Injectable } from '@angular/core';
import { StudentDetail } from './student-detail.model';
import {HttpClient} from "@angular/common/http";
@Injectable({
providedIn: 'root'
})
export class StudentDetailService {
formData :StudentDetail;
readonly rootURL = 'http://localhost:31047/api';
constructor(private http: HttpClient) { }
postStudentDetail(formData:StudentDetail)
{
return this.http.post(this.rootURL+'/StudentDetail',formData)
}
}
I've noticed that the "service" variable in the component seems to be returning null, even though it appears fine in the ngOnInit()
function. I attempted to use the *ngIf="service"
command without success. Any idea why this error keeps popping up? Appreciate any help or insights!