Angular:如何刷新html的一部分form / div / table

问题描述

我有一个用于创建操作的页面。在我的页面中,我有1个表单和2个字段。如果我重新加载页面(或通过代码重新加载window.reload),则可以看到该表单的更新。但是我想通过单击按钮来触发表单刷新。

因此,请帮助我编写一个可以刷新表单(或Tabe / paragraph / etc等任何其他html元素)的函数

.html我的表单:

<form class="was-validated" #zoneForm=ngForm id=#zoneForm>
  <div class=container>
    <div class="row justify-content-center">
      <div class="col-5">
        <div class="card" style="width: 35rem;">
          <div class="card-header">
            <div class="row">
              <div class="col-11">
                Zone Entry
              </div>
              <div class="col-1">
                <i style="margin-left: -1rem;" class="fa fa-arrow-circle-o-right" aria-hidden="true"></i>
              </div>

            </div>

          </div>
          <div class="card-body">

            <div class="row mb-1">
              <div class="col-12">

                <input [(ngModel)]="code" name="code" type="number" class="custom_form_control custom input" placeholder="ID" style="padding: 0px;"
                  disabled>
              </div>
            </div>
            <div class="row mb-1">
              <div class="col-12">

                <input [(ngModel)]="zonename" name="zonename" type="text" class="custom_form_control custom-input" placeholder="Zone Name" required>
                <i class="fa fa-user" style="margin-left: -1rem;font-size: 1rem; color:black;margin-top: 0.25rem;"></i>
              </div>
            </div>

            <div class="row ">
              <div class="col-12 ">
                <button type="button " class="btn btn-outline-primary" style="margin-left: 90%; " (click)="createZone()">Save</button>
              </div>
            </div>

          </div>



          <!-- </div> -->
        </div>
      </div>
    </div>
  </div>


</form>

应通过点击保存按钮

调用函数

解决方法

您可以使用$false

示例:component.ts 文件

ngOnChanges()
,

我建议您使用ReactiveFormModule,因为它功能如此强大,并且是在Angular中使用Forms的最佳方法:

表单示例:

component.ts

public myForm: FormGroup;

  constructor(private fb: FormBuilder) {
    this.myForm = fb.group({
      one: [],two: []
    })
  }

  submit() {
    this.myForm.reset()
  }

component.html

<form [formGroup]="myForm" (ngSubmit)="submit()">
  <input formControlName="one" type="text"/>
  <input formControlName="two" type="text"/>
  <button type="submit">Submit!</button>
</form>

我建议您查看Angular Reactive Form文档: https://angular.io/guide/reactive-forms

看这个例子: https://stackblitz.com/edit/angular-ivy-zevbtg?file=src/app/app.component.html

请记住,不建议使用ngModel在下一版本上使用表单...