Angular 2 FormControl.reset() doesn't work, but .resetForm() does (but typescript error)

爱⌒轻易说出口 提交于 2019-12-25 09:29:25

问题


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?


回答1:


Declare userEditForm as NgFormlike this:

@ViewChild("userEditForm") userEditForm: NgForm;

Now you can access .resetForm() method.




回答2:


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

OnClear(userEditForm: NgForm) {
  userEditForm.reset();
 }


来源:https://stackoverflow.com/questions/44575494/angular-2-formcontrol-reset-doesnt-work-but-resetform-does-but-typescrip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!