Monday, April 5, 2021

Solution 'hasError' is not defined, error TS2531: Object is possibly 'null'.

 Hello, I am trying to create a form with Angular I have this problem:

 

  • Code:
<div class="text-danger"
    *ngIf="productForm.get('productName').hasError('required')">
     
    <span>The name of the products is 
        <strong>obligatory</strong>
    </span>
</div>

 

  • Error:

 

error TS2531: Object is possibly 'null'.

Identifier 'hasError' is not defined. 'AbstractControl | null' does not contain such a memberng

 

  • Solution 1:
<div class="text-danger"
    *ngIf="productForm.get('productName')?.hasError('required')">
     
    <span>The name of the products is 
        <strong>obligatory</strong>
    </span>
</div


  • Solution 2:
<div class="text-danger"
    *ngIf="productForm.controls['productName'].errors?.required">
     
    <span>The name of the products is 
        <strong>obligatory</strong>
    </span>
</div

No comments:

Post a Comment