简体   繁体   English

在声明视图变量之前访问它

[英]Access a view variable before it is declared

My form validation works off the ng classes and in some cases I want to copy the classes up one level to the parent container. 我的表单验证适用于ng类,在某些情况下,我想将这些类向上一级复制到父容器。

<div [ngClass]="{'ng-invalid': input.invalid, 'ng-valid': input.valid, 'ng-pristine': input.pristine}">
  <input [name]="control.id" [(ngModel)]="control.value" required #input="ngModel">
</div>

This works for the most part, but I am getting the following error on the console: 这在大多数情况下都有效,但是在控制台上出现以下错误:

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. 错误:ExpressionChangedAfterItHasBeenCheckedError:检查表达式后,表达式已更改。 Previous value: 'false'. 先前的值:“ false”。 Current value: 'true'. 当前值:“ true”。

Is there a way I can reference a view variable before it is defined? 有没有一种方法可以在定义视图之前引用它?

If you aren't certain that a certain variable will be defined you can use the Elvis operator. 如果不确定是否要定义某个变量,则可以使用Elvis运算符。

<div [ngClass]="{'ng-invalid': input?.invalid, 'ng-valid': input?.valid, 'ng-pristine': input?.pristine}">
  <input [name]="control.id" [(ngModel)]="control.value" required #input="ngModel">
</div>

Perhaps you could create a new component that encapsulates the ngClass and the input? 也许您可以创建一个封装ngClass和输入的新组件? The input.xxx make it look like you should be using FormControls: they do the valid/invalid/pristine stuff for you.. input.xxx使其看起来像您应该使用FormControls:它们为您执行有效/无效/原始的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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