Angular - Невозможно прочесть свойство length, равное null " - PullRequest
0 голосов
/ 08 июля 2020

У меня есть свой 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 is,

<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 : Невозможно прочитать свойство "длина", равное нулю ", когда страница загружается, а не во время начальной загрузки для ввода значения. Кто-нибудь может с этим помочь?

Ответы [ 2 ]

2 голосов
/ 09 июля 2020

Вот для чего нужен оператор безопасной навигации

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

1 голос
/ 09 июля 2020

вы всегда можете это сделать:

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