Consider the Angular Reactive form example below:
<form [formGroup]="form">
<input formControlName="username">
<div *ngIf="form.get('username').invalid">Invalid</div>
</form>
Here is the corresponding component:
export class FormClass {
form = new FormGroup({
username: new FormControl('', Validators.required);
)}
}
To simplify the code for this specific line -
<div *ngIf="form.get('username').invalid">Invalid</div>
We define a get method in the component:
get username() {
return this.form.get('username')
}
Now, we can use the shorter version -
<div *ngIf="username.invalid">Invalid</div>
An interesting observation is why we simply reference the method without actually calling it. Typically, functions are invoked with parentheses like username()
. Is get()
treated differently in this scenario? Apologies for my limited TypeScript knowledge...