简体   繁体   中英

Angular Reactive Form - Button disabled method called twice

I have simple case that show my question.

`

AppComponent.ts

`

`

 formGroup = new FormGroup({
    firstName:new FormControl(''),
    lastName: new FormControl('')
  });

  isValid(){
    console.log(this.formGroup);
    return true;
    
  }

`

`

AppComponent.html

`

`

<form [formGroup]="formGroup">
    <label>FirstName</label>
    <input [formControlName]="'firstName'" />
    <label>Last Name</label>
    <input [formControlName]="'lastName'" />
    <button type="submit" [disabled]="!isValid()" >Submit</button>
</form>

`

My question is, why I see in the console twice output from isValid method?. Is there any reasone for that? and will it impact application performance if I use this way with complex form?

note: I woundring why isValid method called twice?

I am excepting the method to be called once.

Let me explain to you. There is a thing in angular called Change Detection . This is an internal mechanism inside of Angular . This change detection mechanism identified the changes in the UI , input, output properties, and value changes in the properties that are binded to different elements on the UI.

So whenever any change is detected in the whole application, then angular runs a change detection cycle to update all the properties values along with UI.

Now, let's come to your question. You are calling a function in the template which is isValid . So what's happening here is that, whenever any change is detected in the UI then angular is running change detection twice while rendering the whole UI that's why you are seeing the console.log twice.

Why is calling change detection twice?

The answer is, you bind your formGroup in the UI to the form element. So initially, your formGroup is undefined, but later on in your code you are creating a reactive form . So when reactive form gets created then, then the value of formGroup changes from undefined to an actual reactive form object. So in this way, the value of formGroup changes 2 times.

Will it impact the application's performance?

Yes, it will impact the application's peformance drastically, that's why it is recommended in angular, not to call functions directly in html template. Use properties instead. Please read this as a reference to get more understanding

Why you shouldn't use functions in the template

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM