ОШИБКА TypeError: Невозможно прочитать свойство 'значение' из неопределенного в Angular 8 - PullRequest
1 голос
/ 17 марта 2020

Я получаю приведенную ниже ошибку при отправке form.it говорит, что значение не определено при вызове onSubmit. Ошибка и код наклеены ниже. добавлен полный файл HTML. Я кодирую в Angular 8.

EmployeeComponent.html:14 ERROR TypeError: Cannot read property 'value' of undefined
    at EmployeeComponent.onSubmit (employee.component.ts:38)
    at Object.eval [as handleEvent] (EmployeeComponent.html:14)
    at handleEvent (core.js:43993)
    at callWithDebugContext (core.js:45632)
    at Object.debugHandleEvent [as handleEvent] (core.js:45247)
    at dispatchEvent (core.js:29804)
    at core.js:31837
    at SafeSubscriber.schedulerFn [as _next] (core.js:35379)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:185)
    at SafeSubscriber.next (Subscriber.js:124)

HTML Код: EmployeeComponent. html - Добавление полного HTML кода

  <div class="row">
<div class="col s5">

  <form employeeForm="ngform"  (ngSubmit)="onSubmit(employeeForm)">
      <input type="hidden" name="_id" _id="ngModel" [(ngModel)]="employeeService.selectedEmployee._id"/>
      <div class="row">
        <div class="input-field col s12">
           <input type="text"  name="name" #_name="ngModel" [(ngModel)]="employeeService.selectedEmployee.name"> 
          <label>Name: 
              <label class="red-text">*</label>
          </label>
        </div>
      </div>
      <div class="row">
        <div class="input-field col s12">
          <input type="text" name="position" #_position="ngModel" [(ngModel)]="employeeService.selectedEmployee.position" >
          <label>position:
              <label class="red-text">*</label>
          </label>
        </div>
      </div>
      <div class="row">
        <div class="input-field col s12">
          <input type="text" name="office" #_office="ngModel" [(ngModel)]="employeeService.selectedEmployee.office" >
          <label>Office:
              <label class="red-text">*</label>
          </label>
        </div>
      </div>
      <div class="row">
        <div class="input-field col s12">
          <input type="text" name="salary" #_salary="ngModel" [(ngModel)]="employeeService.selectedEmployee._salary" >
          <label>Salary:
              <label class="red-text">*</label>
          </label>
        </div>
      </div>
      <div class="row">
        <div class="input-field col s12">
          <button class="btn btn-custom right"  type="submit">Submit</button>
          <button class="btn btn-custom right" (click)="reset(employeeForm)" type="reset" >Reset</button>
        </div>
      </div>
  </form>
</div>

employee.component.ts

onSubmit(form: NgForm){
     this.employeeService.postEmployee(form.value).subscribe((res)=>{
      this.resetForm(form);
      M.toast({html: 'Saved Successfully!',classess:'rounded'});
    });
  }
}

employee.service.ts

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  selectedEmployee: Employee;
  employees: Employee[];
  readonly baseURL='http://localhost:3000/employees';

  constructor(private http : HttpClient) { }

postEmployee(emp : Employee){
     return this.http.post(this.baseURL, emp);
}

}

1 Ответ

0 голосов
/ 17 марта 2020

Как обсуждалось в комментариях, проблема с кодом заключается в том, что вам нужно добавить # перед employeeForm, это соглашение для определения ссылочной переменной шаблона.

И вторая проблема - орфографическая ошибка ngform. Это должен быть ngForm. Заявление должно выглядеть так:

<form #employeeForm="ngForm"  (ngSubmit)="onSubmit(employeeForm)">

Ниже приведен рабочий стек с базисным кодом c: https://stackblitz.com/edit/angular-wmegcq

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...