1

I am trying to get a way to call a function inside my component only after loading, as long as the component is loaded, several times my function is called and I do not want this, here is my code:

<div class="form-group" [ngClass]="aplicaCssErro('name')">
    <label>
        NAME
    </label>
    <input class="form-control" type="text" formControlName="name" autocomplete="off">
</div>

My function:

verificaValidTouched(campo){
   return !this.formulario_cadastro.get(campo).valid  && this.formulario_cadastro.get(campo).touched;
}

aplicaCssErro(campo){
    console.log(this.verificaValidTouched(campo));

   return{
     'has-error': this.verificaValidTouched(campo),
     'has-feedback': this.verificaValidTouched(campo)
   }
}

The functions only serve to add a validation class in my data-driven form. What I want, is to just call those functions that are in my HTML after I've loaded the page or something better than this, because when loading the page the functions are called several times. Can anyone tell me a solution?

3
  • then you have to call function ones and store class in a variable.angular change detection cycle call these function over and over Commented May 3, 2019 at 17:33
  • this can be done using Subjects take a look at subjects and observables Commented May 3, 2019 at 17:34
  • it happens since this is how angular check bindings. Best practice is seting a variable upon your change and bind that variable. Commented May 3, 2019 at 17:39

1 Answer 1

1

You should utilize an Angular lifecycle hook, probably ngAfterViewInit to call function after the page has finished initializing.

https://angular.io/api/core/AfterViewInit

Lifecycle hooks are a good way of utilizing Angular's API:

https://angular.io/guide/lifecycle-hooks

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.