【问题标题】:How to handle null variable while dealing with two way data binding in Angular 2+如何在Angular 2+中处理两种方式数据绑定时处理空变量
【发布时间】:2018-10-01 07:34:57
【问题描述】:

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

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 变量为addthis.personnel 将被设置为空。

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

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

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

【问题讨论】:

标签: angular angular5 angular2-template


【解决方案1】:

使用猫王运算符?在你的 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得到了回答。

【讨论】:

  • 据我所知。猫王 (?) 运算符不适用于双向绑定
  • 将 [(ngModel)] 用作 [ngModel] 时,elvis 运算符确实有效
  • 但是 [ngModel] 不是用于单向绑定吗?
  • 如果有人能解释一下(ngModelChange)="personnel?.perfullname personnel?.perfullname = $event : null" part,那就太好了
猜你喜欢
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 2019-09-06
  • 1970-01-01
相关资源
最近更新 更多