角度-无法读取null的属性“长度”

时间:2020-07-08 18:33:48

标签: javascript angular typescript angular-reactive-forms

我的我的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错误TypeError:无法读取null的属性'length'”。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

这就是安全导航操作员的目的

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

答案 1 :(得分:1)

您始终可以这样做:

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