[英]Angular2 Forms - ngControl
I'm trying to use ngControl
to apply error classes based on user's input. 我正在尝试使用ngControl
来基于用户的输入应用错误类。
Somehow, I can't make it to work. 不知何故,我无法使其正常工作。 I see that appropriate classes are set (line ng-invalid), but when trying to use name.valid
(where name
is my ngControl) it doesn't work. 我看到已经设置了适当的类(ng-invalid行),但是当尝试使用name.valid
(其中的name
是我的ngControl)时,它不起作用。
html: 的HTML:
<div ngClass="{alert: name.invalid}">
<label for="name">Name</label>
<input ngControl="name" #name id="name" [(ngModel)]="user.name"/>
</div>
</div>
js js
export class App {
userForm: any;
user: any;
constructor(
private _formBuilder: FormBuilder) {
this.user = {name: 'Ben'};
this.userForm = this._formBuilder.group({
'name': ['', Validators.required]
});
}
}
I saw on angular.io examples that they do use it like this (just for other cases, like show/hide divs
)? 我在angular.io示例中看到他们确实像这样使用它(仅在其他情况下,例如show / hide divs
)?
Here's the simple plunker: http://plnkr.co/edit/BKx4yplIOu44tk7Mfolc?p=preview 这是简单的插件: http ://plnkr.co/edit/BKx4yplIOu44tk7Mfolc?p=preview
When input field is empty, I would expect that upper div
gets alert
class, but that doesn't happen. 当输入字段为空时,我希望上层div
获得alert
类,但是不会发生。
In fact there are three things to change in your template: 实际上,模板中需要更改三件事:
ngClass
should be [ngClass]
. ngClass
应该是[ngClass]
。 Otherwise the value is considered as a string and not as an expression. 否则,该值将被视为字符串而不是表达式。 #name
should be #name="ngForm"
. #name
应该是#name
#name="ngForm"
。 Otherwise you reference the DOM element and not the control. 否则,您将引用DOM元素而不是控件。 invalid
property on controls in Angular2 but only a valid
one. Angular2中控件上没有invalid
属性,只有一个valid
属性。 Here is the refactored code: 这是重构的代码:
<div [ngClass]="{alert: !name.valid}">
<label for="name">Name</label>
<input ngControl="name" #name="ngForm"
required id="name" [(ngModel)]="user.name"/>
</div>
Here is the plunkr: http://plnkr.co/edit/OJfb9VDqlrRH4oHXQJyg?p=preview . 这是插件: http ://plnkr.co/edit/OJfb9VDqlrRH4oHXQJyg?p=preview。
Note that you can't leverage of FormBuilder
with ngControl
since the latter allows you to define inline form. 请注意,您不能通过ngControl
FormBuilder
,因为ngControl
允许您定义内联表单。 With FormBuilder
you must use ngFormControl
instead. 使用FormBuilder
,必须改为使用ngFormControl
。
Here is a sample: 这是一个示例:
<div [ngClass]="{alert: !userForm.controls.name.valid}">
<label for="name">Name</label>
<input [ngFormControl]="userForm.controls.name"
id="name" [(ngModel)]="user.name"/>
</div>
See this article for more details: 请参阅本文以获取更多详细信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.