我试图创建一个响应式表单,但此错误“属性‘productForm’没有初始化程序,并且未在构造函数中明确分配。” TypeScript 文件的代码是 -
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-create-product',
templateUrl: './create-product.component.html',
styleUrls: ['./create-product.component.css']
})
export class CreateProductComponent implements OnInit {
productForm:FormGroup;
constructor() { }
ngOnInit(){
this.productForm = new FormGroup({
name: new FormControl(null),
email: new FormControl(null),
number: new FormControl(null),
address: new FormControl(null)
});
}
onSubmit(){
console.log(this.productForm)
}
}
这个对应文件的 HTML 文件是-
<form [formGroup]="productForm" (ngSubmit)="onSubmit()">
<div class="mb-3">
<label class="form-label">Name</label>
<input type="name" class="form-control" formControlName="name"/>
</div>
<div class="mb-3">
<label class="form-label">Email address</label>
<input type="email" class="form-control" formControlName="email" />
</div>
<div class="mb-3">
<label class="form-label">Mobile Number</label>
<input type="number" class="form-control" formControlName="number" />
</div>
<div class="mb-3">
<label class="form-label">Address</label>
<input type="address" class="form-control" formControlName="address" />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
谁能告诉我我能做什么?
答案 0 :(得分:0)
linter 配置的规则,除了在声明属性或构造函数时要初始化的任何属性。
您可以更改规则或将初始化移动到构造函数(或声明):
productForm:FormGroup;
constructor() {
this.productForm = new FormGroup({
name: new FormControl(null),
email: new FormControl(null),
number: new FormControl(null),
address: new FormControl(null)
});
}
ngOnInit() {
}