Angular 2 FormControl.reset() doesn't work, bu

2019-08-18 09:02发布

In my Angular 2 form, I have the following typescript:

export class UserEditComponent implements OnChanges {
    @Input() userModel: IUserModel;
    @Output() onSave: EventEmitter<IUserModel> = new EventEmitter<IUserModel>();

    @ViewChild("userEditForm") userEditForm: FormControl;

    private userNameIsValid = true;

    constructor(private httpService: HttpService) {
    }

    ngOnChanges (changes: SimpleChanges) {
        this.userEditForm.resetForm();
        console.log(this.userEditForm);
    }

    ....
}

and template html:

<form class="form-horizontal" #userEditForm="ngForm" (ngSubmit)="onSaveUser()" novalidate>
    ....
</form>

I tried using the .reset() function, but it did nothing. The .resetForm actually resets the _submitted property of the form from true back to false, however, it gives me a TypeScript error Property resetForm does not exist on type FormControl.

First, is resetForm an actual function that works? I can't seem to find any documentation for it... but it works and .reset() doesn't.

Second, how can I get rid of this TypeScript error? Do I need to update my typings for Angular 2?

2条回答
Bombasti
2楼-- · 2019-08-18 09:26

Declare userEditForm as NgFormlike this:

@ViewChild("userEditForm") userEditForm: NgForm;

Now you can access .resetForm() method.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-18 09:45

You should import NgForm from @angular/forms and try this.

OnClear(userEditForm: NgForm) {
  userEditForm.reset();
 }
查看更多
登录 后发表回答