【问题标题】:Angular - Cannot read property 'length' of null"Angular - 无法读取 null 的属性“长度””
【发布时间】:2020-07-09 07:55:55
【问题描述】:

我的component.cs如下:

import { Component, VERSION } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  profileForm = new FormGroup({
    message: new FormControl(''),
  });

  get message(): FormControl {
    return this.profileForm.get('message') as FormControl;
  }
}

component.html 是,

<form [formGroup]="profileForm">
  <textarea rows="5"
  cols="100"
  maxlength="500"
  formControlName="message"
  class="form-control">
</textarea>
</form>

{{message.value.length}} of 500 characters

当页面加载而不是在初始加载输入值期间,我收到“core.js:4098 ERROR TypeError: Cannot read property 'length' of null”。有人可以帮忙吗?

【问题讨论】:

  • 显然,message.value 为 null,因为这是您访问 .length 属性的唯一位置。你有什么办法解决这个问题?
  • 你可以试试{{message.value?.length}}
  • @ShamPooSham 是 angularJS 中的三元运算符吗?对不起,我是新人...如果三元,他们是否允许“:”不为空?因为我使用了相同的方法,并且它适用于我上面提供的案例。但是其他条件不显示 0
  • 首先,它是 Angular,而不是 AngularJS。它们实际上是两种不同的东西。 AngularJS 用于指代旧的、基于 javascript 的框架(版本 1.x)。 Angular 用于指代较新的、基于打字稿的框架(版本 2+)。现在,?. 是安全导航操作员。它不是三元运算符,但您也可以使用三元 x ? y : z 运算符。你也可以使用|| 做你想做的事,像这样:{{message.value?.length || 0}}
  • 您可以在此处阅读有关安全导航运算符的更多信息angular.io/guide/…

标签: javascript angular typescript angular-reactive-forms


【解决方案1】:

这就是安全导航运算符的作用

{{message?.value?.length || 0}} of 500 characters

【讨论】:

    【解决方案2】:

    你总是可以这样做:

    <span *ngIf="message && message.value">{{message.value.length}}</span> of 500 characters
    

    【讨论】:

      猜你喜欢
      • 2018-03-27
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 2013-03-21
      • 2015-04-06
      • 2019-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多