Search code examples
javascriptangulartypescriptangular-reactive-forms

Angular - Cannot read property 'length' of null"


I have my component.cs as follows:

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

I am getting "core.js:4098 ERROR TypeError: Cannot read property 'length' of null" when the page loads and not during the inital load to enter value. Can someone help with this?


Solution

  • That is what the safe navigation operator is for

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