我有一个用于编辑产品的表单,其中包含名称、类别和价格。我有 2 个硬编码产品和 2 个按钮,“加载产品一”和“加载产品二”。当我点击“加载产品一”,编辑产品,然后保存(如图一所示)时,我无法再加载产品(见图2)。当我第二次点击“加载产品一”时,保存后没有任何反应。
在图 2 中,我在保存产品一后单击了加载产品一:
如果我在保存产品 1 后加载产品 2,它确实有效。只加载相同的产品两次是行不通的。我认为这与 ngDoCheck()
有关。这里遵循我的组件类和我的模板:
export class AppComponent {
products: Product[] = [];
product: Product = new Product();
productOne: Product;
productTwo: Product;
productToLoad: number = 0;
constructor() {
this.createProducts();
}
createProducts() {
this.productOne = new Product();
this.productOne.id = 1;
this.productOne.name = 'productOne';
this.productOne.category = 'soccer';
this.productOne.price = 5.5;
this.productTwo = new Product();
this.productTwo.id = 2;
this.productTwo.name = 'productTwo';
this.productTwo.category = 'basketball';
this.productTwo.price = 8.6;
this.products.push(this.productOne);
this.products.push(this.productTwo);
}
submitForm(form: NgForm) {
if (form.valid) {
// this.model.saveProduct(this.product);
this.product = new Product();
form.reset();
}
}
ngDoCheck() {
this.product = new Product();
Object.assign(this.product, this.products[this.productToLoad]);
}
resetForm() {
this.product = new Product();
}
setProduct(key: number) {
this.productToLoad = key;
}
}
这是我的模板:
<form novalidate #form="ngForm" (ngSubmit)="submitForm(form)" (reset)="resetForm()">
<div class="form-group">
<label>Name</label>
<input class="form-control" name="name"
[(ngModel)]="product.name" required />
</div>
<div class="form-group">
<label>Category</label>
<input class="form-control" name="category"
[(ngModel)]="product.category" required />
</div>
<div class="form-group">
<label>Price</label>
<input class="form-control" name="price"
[(ngModel)]="product.price"
required pattern="^[0-9\.]+$" />
</div>
<button type="submit" class="btn btn-primary m-1"
[class.btn-warning]="true" [disabled]="form.invalid">
save
</button>
<button type="reset" class="btn btn-secondary m-1">Cancel</button>
</form>
<button (click)="setProduct(0)">load product one</button>
<button (click)="setProduct(1)" >load Product two</button>
答案 0 :(得分:1)
您应该使用 Angular Reactive Forms。它将极大地简化您的代码(请参阅:pachValue()
)并且允许您使用验证器:
export class AppComponent {
// Add validors if needed
productFormGroup = this.fb.group({
id: [],
name: [],
category: [],
price: []
});
private products: Product[] = [
new Product(/*...*/),
new Product(/*...*/)
];
constructor(private fb: FormBuilder) {}
submitForm() {
if (this.productFormGroup.valid) {
// Do something with this.productFormGroup.value
}
}
resetForm() {
this.productFormGroup.reset();
}
setProduct(key: number) {
this.productFormGroup.patchValue(this.products[key]);
}
}