Здравствуйте, я пытаюсь отправить форму, в которой есть только одно поле, используя Angular 7, но я получаю эту ошибку в строке ввода:
ОШИБКА TypeError: Cannot read property ' Имя 'из неопределенного
Мой HTML выглядит так:
<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>
У меня есть компонент, который выглядит следующим образом:
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)
}
);
}
}
И Служба выглядит следующим образом:
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)
}
}
Я понимаю, что переменная "service" компонента возвращает значение NULL, но при печати в функции ngOnInit()
значение не равно NULL. Я попытался использовать команду *ngIf="service"
безуспешно, поэтому я не знаю, почему эта ошибка отображается. Кто-нибудь знает, что я делаю не так?