Search code examples
htmlangularangular8angular-reactive-forms

Compilation error when trying to add "?" operator


The following code snippet works fine.

<div class="alert alert-danger" role="alert" *ngIf="formulario.get('email')?.errors['required']">
    Please inform the email
</div>

However, when I try to add a ? to check if errors exist, I get a compilation error. The code below gives an error:

<div class="alert alert-danger" role="alert" *ngIf="formulario.get('email')?.errors?.['required']">
            Please inform the email
</div>

Output:

Uncaught Error: Template parse errors: Parser Error: Unexpected token [, expected identifier or keyword at column 34 in [formulario.get('email')?.errors?.['required']] in ng:///AppModule/LoginComponent.html@12:55 (")" #form="ngForm" [formGroup]="formulation">

"devDependencies": {
    "@angular-devkit/build-angular": "~0.803.19",
    "@angular/cli": "^8.3.29",
    "@angular/compiler-cli": "~8.2.14",
    "@angular/language-service": "~8.2.14",
    "@types/chartist": "^0.9.46",
    "@types/datatables.net": "^1.10.17",
    "@types/jasmine": "~3.3.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/jquery": "^3.3.31",
    "@types/node": "~8.9.4",
    "codelyzer": "^5.0.0",
    "jasmine-core": "~3.4.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.1.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.15.0",
    "typescript": "~3.4.3"
  }

Solution

  • After downgrading to Angular 8, it is able to reproduce the issue mentioned. It is more likely that your current syntax is not compatible with the old Angular version.

    As an alternative, work with the && operator which works the same with the optional chaining (?.).

    <div
      class="alert alert-danger"
      role="alert"
      *ngIf="
        formulario &&
        formulario.get('email') &&
        formulario.get('email').errors &&
        formulario.get('email').errors['required']
      "
    >
      Please inform the email
    </div>
    

    Demo @ StackBlitz