Angular 8- 双向数据绑定,空值

Angular 8- two way data binding, null values

我在双向数据绑定和 Angular 8

方面遇到问题

在下面的示例中,我的模型 (service.formData) 已填充,但其中一个变量(实际上是子 table)为 null(service.formData.ProjectSshaspModel) 如果我在数据库中填充数据,则两种方式的绑定似乎都可以正常工作并检索并传回数据。但是当页面加载时变量为 null 并且我填充模型(HTML 页面)时,对象似乎没有被填充

我已将 HMTL、Angular 双向数据绑定和 JSON 值放在下面。如果可能请帮忙。谢谢

 <form #form="ngForm" autocomplete="off" (submit)="OnSubmit(form)" *ngIf="service.formData">
  <div class="row" id="section1">
    <div class="col-md-10">

      <input type="hidden" name="ProjectID" #ProjectID="ngModel" [(ngModel)]="service.formData.ProjectID" />
      <input type="hidden" name="ProjectSshaspModel.ProjectSshaspID" #ProjectSshaspModel.ProjectSshaspID="ngModel" [(ngModel)]="service.formData.ProjectSshaspModel.ProjectSshaspID" />
        <input type="radio" id="not-required"
               name="CompanyLogoRequired" #ProjectSshaspModel.CompanyLogoRequired="ngModel" [(ngModel)]="service.formData.ProjectSshaspModel && service.formData.ProjectSshaspModel.CompanyLogoRequired" ng-checked="(CompanyLogoRequired==0)" [value]="0" />
        Not Required
        &nbsp;
        <input type="radio" id="incorporate"
               name="CompanyLogoRequired" #ProjectSshaspModel.CompanyLogoRequired="ngModel" [(ngModel)]="service.formData.ProjectSshaspModel && service.formData.ProjectSshaspModel.CompanyLogoRequired" ng-checked="(CompanyLogoRequired==1)" [value]="1" />
        Incorporate


{
"projectModel": {
    "ProjectSshaspModel": null,
    "ProjectID": "a9400d92-de37-4c00-957e-08d7bbd4b4c5",
    "ProjectNumber": "2020-1233",
    "Consultant": "Joe Test",
    "AssignedDate": "2020-02-28T00:00:00",
    "ClientDueDate": "2020-02-29T00:00:00",
    "ProjectCreationDate": "2020-02-28T00:00:00",
    "ScopeOfWork": "Scope of work",
    "Service": 0,
    "ClientName": "Ebay",
    "CompanyContact": "John Smith",
    "CompanyContactPhone": "555-555-5555",
    "CompanyContactEmail": "jsmith@comcast.net",
    "CompanyAddress": "123 Sesame Place Test, JN 01111",
    "CompanyType": 2
}

}

假设你的 ngModel 是用变量 service.formData.ProjectSshaspModel.ProjectSshaspID 定义的,那么它要求只有最终变量为 null,以前的属性不能是 null(在这种情况下 ProjectSshaspID 只能是 null。所以我建议在组件初始化时初始化变量,如下所示。

service.ts

this.formData.ProjectSshaspModel = {};

还有为什么你的 ngModel 错误地定义了两个变量。

[(ngModel)]="service.formData.ProjectSshaspModel && service.formData.ProjectSshaspModel.CompanyLogoRequired"

ngModel只需要一个变量更新,所以改成一个变量

[(ngModel)]="service.formData.ProjectSshaspModel.CompanyLogoRequired"