im getting this error after data binding the _id property. can anyone help me out.
CODE:
<div class="form-group">
<input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="iphoneService.selectedIphone._id">
</div>
Here IS THE iphone.Service Code
import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { Iphone } from "./iphone.model";
@Injectable()
export class IphoneService {
selectedIphone: Iphone;
iphones: Iphone[];
readonly baseUrl = "http://localhost:3000/iphone";
constructor(private http: HttpClient) {}
postIphone(iphon: Iphone) {
return this.http.post(this.baseUrl, iphon);
}
}
HERE IS THE iphon.model
export interface Iphone {
_id: string;
firstName: string;
lastName: string;
email: string;
colorPrefence: string;
contact: string;
country: string;
state: string;
city: string;
zipCode: string;
transactionId: string;
__v: string;
}
Here is the iphone.component.ts
@Component({
selector: "app-iphone",
templateUrl: "./iphone.component.html",
styleUrls: ["./iphone.component.css"],
providers: [IphoneService]
})
export class IphoneComponent implements OnInit, AfterViewChecked {
constructor(public iphoneService: IphoneService) {}
ngOnInit() {}
onSubmit(form: NgForm) {
this.iphoneService.postIphone(form.value).subscribe(res => {});
}
I think the Error I'm getting is due to incorect binding of the model but i'm unable to figure out how to solve it.
You have several problems in the way you are working out your workflow.
First you are trying to do a bind to a variable that exists in the service and not in the component. Services should not be responsible for storing view state. View state should be responsibility of the component. You would need to have a variable on your component (e.g. selectedIphoneId
) and then you can your use that in your [(ngModel)]
.
Also remove the assignment of the template reference #_id=“ngModel
. If you don’t even need to use it get rid of it. You would have something like this:
<div class="form-group">
<input type="hidden" name="_id" #_id [(ngModel)]="selectedIphoneId">
</div>