简体   繁体   English

重置表格(反应形式)

[英]Reset Form (Reactive Forms)

This is the HTML: 这是HTML:

<div class="container">
  <ng-template [ngIf]="userIsAuthenticated">
    <form [formGroup]='form' name="test">
      <div class="form-group">
        <input type="text" class="form-control" name="header" placeholder="Post Header" formControlName="header">
      </div>
      <div class="input-group">
        <textarea class="form-control" rows="3" name="message" placeholder="Post Message" formControlName="message"></textarea>
      </div>
      <div class="form-group">
        <input class="form-control-file" type="file" id="file1" ng-model="test1" (change)="onFilePicked($event)">
      </div>
      <button class="btn btn-success btn-sm" id="postbtn" type="button" [disabled]="!form.valid" (click)="onSavePost()">{{ btnText }}</button>
    </form>
  </ng-template>
</div>

There is more to it but I use this to reset the form in the TS file: 还有更多内容,但是我可以使用它来重置TS文件中的表单:

this.form.reset();

This resets everything apart from the file. 这将重置文件以外的所有内容。

I created this in the mean time to remove the file: 我在创建此文件的同时删除了该文件:

<button ng-click="angular.copy(file1)" #filePicker id="file2" type="reset">Remove files</button> But using this didnt seem like good practice. <button ng-click="angular.copy(file1)" #filePicker id="file2" type="reset">Remove files</button>但是,使用此方法似乎<button ng-click="angular.copy(file1)" #filePicker id="file2" type="reset">Remove files</button>好习惯。

I have also tried this in the ts file. 我也在ts文件中尝试过此操作。 this.form.value.file.nativeElement.value = '';

This seems to reload the page, which is not good. 这似乎重新加载了页面,这不好。

Any advice would be great PLEASE only contributional comments. 任何建议都是很棒的, 仅提供贡献性的意见。

Start by binding your input to avalie model with 首先将您的输入绑定到avalie模型

<input ng-model="test1"> --> <input [(ngModel)]="test1" #fileInput>

And to reset it, declare it as a view child, then reset it like this 并重置它,将其声明为视图子级,然后像这样重置它

@ViewChild('fileInput') fileInput: ElementRef;

resetForm() {
  this.form.reset();
  this.fileInput.nativeElement.value = undefined;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM