FromZeroToHero FromZeroToHero - 3 years ago 86
TypeScript Question

How get() works in Typescript

Say we have Angular Reactive form:

<form [formGroup]="form">
<input formControlName="username">
<div *ngIf="form.get('username').invalid">Invalid</div>

And component:

export class FormClass {
form = new FormGroup({
username: new FormControl('', Validators.required);

To make this line shorter -
<div *ngIf="form.get('username').invalid">Invalid</div>

We add a get method to the component:

get username() {
return this.form.get('username')

So now we can do -
<div *ngIf="username.invalid">Invalid</div>

I wonder why we don't call this method? We just pass it as a kind of object - without
. I mean this method is a function and function gets invoked like this
. Is
somehow special in this case? Sorry for my bad TS knowledge...

Answer Source

Because by adding get makes it a getter and can be accessed (read) like a field. This is a TypeScript feature.

With set you can create a matching setter and with both you can read and set it like a field.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download