Angular 错误类型错误:无法读取属性'_id';未定义在Object.eval[作为updateDirectives]的值

Angular 错误类型错误:无法读取属性'_id';未定义在Object.eval[作为updateDirectives]的值,angular,angular-ngmodel,Angular,Angular Ngmodel,在数据绑定_id属性后,我收到此错误。有人能帮我吗 代码: <div class="form-group"> <input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="iphoneService.selectedIphone._id"> </div> 这是iphon.model export interface Iphone { _id: string; firstName: string;

在数据绑定_id属性后,我收到此错误。有人能帮我吗

代码:

<div class="form-group">
  <input type="hidden" name="_id" #_id="ngModel" [(ngModel)]="iphoneService.selectedIphone._id">
</div>
这是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;
}

这是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 => {});
}


我认为我遇到的错误是由于模型绑定不正确,但我无法找到解决方法。

您在制定工作流程时遇到了几个问题

首先,您尝试绑定到服务中而不是组件中存在的变量。服务不应负责存储视图状态。视图状态应由组件负责。组件上需要有一个变量(例如,
selectedIphoneId
),然后可以在
[(ngModel)]
中使用该变量

还要删除模板引用的分配。如果您甚至不需要使用它,请将其删除。您可以使用以下内容:

<div class="form-group">
    <input type="hidden" name="_id" #_id [(ngModel)]="selectedIphoneId">
  </div>


谢谢您的回复,我尝试过按您的建议放置?但不起作用,我将在上面附加我正在使用的iphone.service文件。啊,等等,为什么您有模板引用?#u id=“ngModel”?请删除它。如果您需要模板引用,只需保留#u id,其他什么都不保留。同样的错误如下:(,我已附加了上面的iphone.service文件,是否有问题?我需要查看您的组件。服务没有告诉我太多。您将数据分配给selectedIphone的位置?我已将上面的iphone.model附加到OP
<div class="form-group">
    <input type="hidden" name="_id" #_id [(ngModel)]="selectedIphoneId">
  </div>