![](/img/trans.png)
[英]How to use input field value attribute while using formControlName? [Angular]
[英]How to use validator to change border color of formcontrolname in angular
我有一個表單控件,我想在字段無效時更改顏色我嘗試了以下操作,因為大多數示例都是這樣做的:
<input
formControlName="personNameField"
type="text"
placeholder="Bitte eingeben"
[ngClass]="{'error': personNameField.errors}"
></input>
我的 ts formcontrol 是這樣生成的:
form = this.builder.group({
personNameField: new FormControl('',
[Validators.required]),
});
getName(){
this.form.get('personNameField')
}
但我收到以下錯誤:
ERROR TypeError: Cannot read properties of undefined (reading 'errors')
知道我做錯了什么嗎?
更新:我添加了吸氣劑並刪除了問號,但邊界仍然不起作用,只顯示錯誤消息。
更新2:
.error {
// underline input field on error
border: 1px solid red;
display: block;
color: red;
}
嘗試這個。
[ngClass]="{'error': form.get('personNameField')?.errors}"
使用引導程序 class 進行輸入驗證非常簡單:首先在 HTML 文件中,我們有:
<div class="form-group">
<label for="title">title</label>
<input id="title" type="text" formControlName="title" class="form-
control" [ngClass]="{'is-invalid': isCategorySubmitted &&
categoryFormInfo.title.errors}" />
</div>
所以在你的 ts 文件中:
isCategorySubmitted = false;
initFormBuilder() {
this.categoryForm = this.formBuilder.group({
title: ['', Validators.required]
});
}
get categoryFormInfo() {
return this.categoryForm.controls;
}
submit() {
this.isCategorySubmitted = true;
if (this.categoryForm.invalid) {
return;
}
// do your code after the submit
}
這樣,您可以簡單地驗證輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.