0

Hi i am looking at the following Angular code, which is an error message div if the user does not enter their name in the Name field.

<div *ngIf ="userName.errors?.required && username.touched" class="alert alert-danger"> Name is required</div>

I understand that this div will show if the Name field is touched and the username has not been entered in the Name field

But I'm not sure i follow the ?. syntax. How should i read it.

Thanks

Nosail
  • 465
  • 2
  • 7
  • 19

3 Answers3

3

It's called the Safe Navigation Operator. It's used if you expect an object to be possibly null and you need to access its properties. That is to prevent an error which is caused by accessing properties of null values.

Rax Weber
  • 3,730
  • 19
  • 30
  • got it... and thanks for the link... a quick follow-up query... in the ngIf why can't we just check for `userName.required` as opposed to `userName.errors?.required` – Nosail Aug 17 '17 at 03:50
  • 1
    Because based on [Angular Form Validation](https://angular.io/guide/form-validation), `errors` is a list of validation errors (e.g. `required`, `minlength`) that you can use to validate your inputs. – Rax Weber Aug 17 '17 at 03:56
1

this ?. means that only check this property if it have value, in other words, this will ignore it if userName.errors for any reason is undefined.

Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
0

In C# , it is called Null Propagation. See below codes, they express the same meaning.

var name = _currentTpl != null ? _currentTpl.TplName : null;

var name = _currentTpl?.TplName; 

In Angular , it is called safe navigation operator. Actually, there is no difference.

39ecneret
  • 661
  • 3
  • 7
  • 17