@Component({
template: `
<form [formGroup]="formGroup" (ngSubmit)="onSubmit()" novalidate>
<textarea name="detail" id="detail" formControlName="detail"></textarea>
<div *ngIf="formGroup.controls['detail'].dirty && formGroup.controls['detail'].invalid">This is required</div>
<button type="submit" >Post</button>
</form>
`,
})
export class CreateDiscussionComponent {
formGroup: FormGroup;
submitted: boolean = false;
constructor(
) {
this.formGroup = new FormGroup({
detail: new FormControl('', [Validators.required, Validators.minLength(2) ]),
type : new FormControl('discussion'),
userPosts: new FormControl([])
});
}
onSubmit(): void {
console.log('form data', this.formGroup.value)
this.submitted = true;
this.formGroup.reset()
}
}
使用此代码。当我第一次在控制台中获得此对象时提交表单
{
detai: 'my text'
type: 'discusion'
userPosts: []
}
第二次,每次我得到这个
{
detai: 'my text'
type: null
userPosts: null
}
我期待type = discussion
和userposts = []
答案 0 :(得分:4)
FormGroup的reset方法不会将值重置为预定义值,它会重置为null并重置状态(pristine,untouched)。要使用预定义值重置状态,您必须再次设置值,如下所示:
this.form.reset({
type: 'discussion',
userPosts: []
});
参考:https://angular.io/docs/ts/latest/api/forms/index/FormGroup-class.html#!#reset-anchor