在 Angular 2+ 中处理双向数据绑定时如何处理空变量

How to handle null variable while dealing with two way data binding in Angular 2+

我正在使用相同的组件进行编辑以及添加新条目。

if(this.action='edit'){
    this._PersonnelService.getUsersById(this.selectedperid)
      .subscribe((userdata: Iuser) => { this.personnel = userdata[0]; this.personnel.perid = this.selectedperid;console.log(userdata[0]); }, (error) => {
        this.statusMessage = 'Problem with service. Please try again.'
        console.error(error);
      });
   }
    else{     this.personnel=null}

  }

这意味着如果 this.action 变量是 add this.personnel 将被设置为空。

现在 HTML 我有一些元素,例如 :

<input type="text"   class="form-control" name="PerFullName"  
[(ngModel)]="personnel.perfullname" id="fullname ">

我在控制台中遇到了一大堆错误。我的文本框不可见。
我该如何解决?

使用 elvis 运算符?在你的 html

<input type="text"   class="form-control" name="PerFullName"  
[ngModel]="personnel?.perfullname" (ngModelChange)="personnel?.perfullname personnel?.perfullname = $event : null" id="fullname ">

还有??在您的 javascript 中设置默认值以防 null

const j = null
y = j ?? 'Anonymous'

之前已经在这里回答过 two-way-binding-with-elvis-operator