Я создаю форму, в угловых 2. Моя цель-получить данные от API и передать его в форму для редактирования. Однако, я бегу в эту ошибку:
исключение: Неперехваченные (обещанию): ошибка: Ошибка в ./Класс EditPatientComponent EditPatientComponent - встроенный шаблон:1:10 вызвана: formGroup ожидает FormGroup экземпляр. Пожалуйста, передайте один.
Вот текущий код с ошибкой.
в формате HTML
<section class="CreatePatient">
<form [formGroup]="patientForm" (ngSubmit)="onSubmit()">
<div class="row">
<div class="form-group col-12 col-lg-3">
<label for="firstName">First Name</label>
<input formControlName="firstName" type="text" class="form-control" id="firstName" >
</div>
<div class="row">
<div class="col-12 col-lg-2">
<button type="submit" name="submit" class="btn btn-block btn-primary">Save</button>
</div>
</div>
</form>
</section>
ТС
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { PatientService } from './patient.service';
import { Patient } from './patient';
@Component({
templateUrl: 'editpatient.component.html'
})
export class EditPatientComponent implements OnInit {
errorMessage: string;
id: string;
editMode = true;
private patientForm: FormGroup;
private patient: Patient;
constructor(
private patientService: PatientService,
private router: Router,
private activatedRoute: ActivatedRoute,
private formBuilder: FormBuilder) {
console.log("routes");
console.log(activatedRoute.snapshot.url[1].path);
}
ngOnInit() {
this.getPatient();
}
getPatient() {
this.patientService.getPatient(this.activatedRoute.snapshot.url[1].path)
.subscribe(
patient => {
this.id = this.activatedRoute.snapshot.url[1].path;
this.patient = patient;
this.initForm();
},
error => this.errorMessage = <any>error);
}
onSubmit(form){
console.log(this.patientForm);
// Post the API
};
initForm() {
let patientFirstName = '';
if (this.editMode) {
console.log(this.patient.firstName);
console.log(this.patient.lastName);
console.log(this.patient.participantUuid);
patientFirstName = this.patient.firstName;
}
this.patientForm = new FormGroup({
'firstName': new FormControl(patientFirstName)
})
};
}
Любая помощь/указывая мне в правильном направлении было бы здорово! Спасибо!
Ваш patientForm
это не определено
до пациента
в подписке заполняется. Таким образом, вы'вновь пытается привязать к значению, которое не'т существуют в шаблоне, когда шаблон парсится.
Добавить *ngIf
для отображения формы только тогда, когда пациент находится истина, или группа форма создается:
<section class="CreatePatient">
<form *ngIf="patient" [formGroup]="patientForm" (ngSubmit)="onSubmit()">
<div class="row">
<div class="form-group col-12 col-lg-3">
<label for="firstName">First Name</label>
<input formControlName="firstName" type="text" class="form-control" id="firstName" >
</div>
<div class="row">
<div class="col-12 col-lg-2">
<button type="submit" name="submit" class="btn btn-block btn-primary">Save</button>
</div>
</div>
</form>
</section>
Когда пациента заполняется в подписке patientForm
экземпляр будет существовать и привязки будут работать. Это's в общем-то "попался" при общении с async значения.
Формы Дон'т всегда имеют начальные значения, так что вы также можете проверить существование самой формы:
<form *ngIf="patientForm" [formGroup]="patientForm" (ngSubmit)="onSubmit()">
Важной частью является то, что форма-это'т, оказанных до его создания.
Проблема в том, что ваша форма является нулем в начале.
И только на НГ инициализации вы получите пациента и затем создать его. Вы должны инициализировать виде на начало или
<section class="CreatePatient" *ngIf="patientForm">
Ребята, которые сталкиваются с проблемами с реактивной формы Первый в своем компоненте.файл TS убедитесь, что вы импортировать следующие:
import { FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
export class NewsfeedformComponent implements OnInit {
NewsfeedForm: FormGroup;
constructor(private _formBuilder: FormBuilder){}
ngOnInit() {
this.lookupService.getStatus().subscribe((status: IStatus) => {
this.status = status;
});
this.NewsfeedForm = this._formBuilder.group({
NewsfeedID: [0,null],
StatusID: ['', Validators.required],
publishdate: ['', Validators.required]
})
}
}
в компонент HTML-файл
<form class="form-container" [formGroup]="NewsfeedForm"
#newsFeedform="ngForm" (ngSubmit)="form1()">
<div id="rowTwo" fxLayout="row" fxLayout.lt-md="column" fxLayoutGap="20px" fxLayoutGap.lt-md="0px">
<mat-form-field appearance="outline">
<mat-label>Status</mat-label>
<mat-select formControlName="StatusID" required>
<mat-option></mat-option>
<mat-option *ngFor="let itemofStatus of status" [value]="itemofStatus.StatusID">
{{itemofStatus.Status}}
</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<input matInput [matDatepicker]="publishdate" placeholder="Publish Date"
formControlName="publishdate">
<mat-datepicker-toggle matSuffix [for]="publishdate"></mat-datepicker-toggle>
<mat-datepicker #publishdate></mat-datepicker>
</mat-form-field>
</div>
</форма>