【问题标题】:Problem with function on the Angular componentAngular 组件上的功能问题
【发布时间】:2019-05-03 17:30:56
【问题描述】:

我试图找到一种方法,仅在加载后才在我的组件内调用函数,只要加载了组件,我的函数就会被调用几次,我不希望这样,这是我的代码:

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

我的功能:

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)
   }
}

这些函数仅用于在我的数据驱动表单中添加一个验证类。我想要的是在我加载页面或比这更好的东西之后调用那些在我的 HTML 中的函数,因为在加载页面时,函数会被多次调用。谁能告诉我一个解决方案?

【问题讨论】:

  • 那么你必须调用函数并将类存储在一个变量中。角度变化检测循环一遍又一遍地调用这些函数
  • 这可以使用Subjects 来完成,看看主题和可观察对象
  • 发生这种情况是因为这是角度检查绑定的方式。最佳做法是根据您的更改设置一个变量并绑定该变量。

标签: angular


【解决方案1】:

您应该使用 Angular 生命周期钩子,可能是 ngAfterViewInit 在页面完成初始化后调用函数。

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

生命周期钩子是利用 Angular API 的好方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-23
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多