[英]Changing Input Element CSS based on Angular Reactive Forms validation
I have a simple reactive form like this: 我有一个简单的反应形式,像这样:
this.loginForm = this._fb.group({
email: ['', [Validators.required, Validators.pattern('^[A-Za-z0-9._%+-]+@gmail.com$')]],
password: ['', Validators.required]
});
The on HTML: 在HTML上:
<!------------------------- PASSWORD FIELD ------------------------->
<div class="uk-margin">
<input type="password" class="uk-input"
placeholder="Enter Password" formControlName="password">
<!----- VALIDATION WARNINGS ----->
<div *ngIf="loginForm.get('password').touched">
<div *ngIf="loginForm.get('password').hasError('required')">
<div class="uk-text-danger"> Password is required.</div>
</div>
</div>
</div>
Then in CSS: 然后在CSS中:
.ng-valid[required] {
border: 5px solid #42A948;
}
.ng-invalid[required] {
border: 5px solid red;
}
The ng-valid/invalid
CSS is being applied. 正在应用
ng-valid/invalid
CSS。 I want to change the colour of the input fields border. 我想更改输入字段边框的颜色。 But the CSS does not work form me.
但是CSS对我不起作用。 What am I doing wrong?
我究竟做错了什么?
Update: 更新:
ng-invalid and ng-valid are always applied, you can customize css further to resolve this. 始终应用ng-invalid和ng-valid,您可以进一步自定义css来解决此问题。
ng-valid.ng-touched {
border: 5px solid #42A948;
}
ng-invalid.ng-touched {
border: 5px solid red;
}
You could use [ngClass]
for the conditional class based on the error. 您可以根据错误将
[ngClass]
用于条件类。 For example: 例如:
<!------------------------- PASSWORD FIELD ------------------------->
<div class="uk-margin">
<input
type="password"
class="uk-input"
placeholder="Enter Password"
formControlName="password"
[ngClass]="{'has-error': loginForm.get('password').touched && loginForm.get('password').hasError('required')}">
<!----- VALIDATION WARNINGS ----->
<div *ngIf="loginForm.get('password').touched">
<div *ngIf="loginForm.get('password').hasError('required')">
<div class="uk-text-danger"> Password is required.</div>
</div>
</div>
</div>
Then in CSS: 然后在CSS中:
uk-input.has-error{
/* your styles */
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.