【发布时间】:2021-10-21 02:23:16
【问题描述】:
我尝试在 Angular 中进行反应式表单验证,但出现错误。我的目标是让程序在用户将必填字段留空时警告用户。
product-add-forms2.component.ts
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Product } from '../product';
@Component({
selector: 'app-product-add-forms2',
templateUrl: './product-add-forms2.component.html',
styleUrls: ['./product-add-forms2.component.css']
})
export class ProductAddForms2Component implements OnInit {
constructor(private formBuilder: FormBuilder) { }
productAddForm: FormGroup;
product: Product = new Product();
createProductAddForm() {
this.productAddForm = this.formBuilder.group({
name: ["", Validators.required],
description: ["", Validators.required],
imageUrl: ["", Validators.required],
price: ["", Validators.required],
categoryId: ["", Validators.required],
});
}
ngOnInit(): void {
this.createProductAddForm();
}
add() {
if (this.productAddForm.valid) {
this.product = Object.assign({}, this.productAddForm.value)
}
}
}
product-add-forms2.component.html
<h3>New Product - Reactive</h3>
<form [formGroup]="productAddForm" (ngSumbit)="add()" class="form-group">
<div>
<input type="text" id="name" name="name" formControlName="name" class="form-control" placeholder="Ürün Adı">
<div class="alert alert-danger"
*ngIf="productAddForm.get('name').hasError('required') && productAddForm.get('name').dirty">Product name is required
</div>
</div>
</form>
当我运行它的显示错误时
<div class="alert alert-danger"
*ngIf="productAddForm.get('name').hasError('required') && productAddForm.get('name').dirty">Product name is required
</div>
我正在谈论的部分 (hasError) 和 (dirty)
【问题讨论】:
-
你能创建 stackblitz 工作样本吗?
-
@YongShun 我找不到任何解决方案。
-
@AlirezaAhmadi 抱歉,我不知道该怎么做。我是这份工作的新手。
-
我把你的代码放在这里:stackblitz.com/edit/…,我看不到任何错误
标签: angular angular-reactive-forms reactive-forms