【问题标题】:Set initial value to a Toggle of a form in Angular Material within HTML将初始值设置为 HTML 中 Angular Material 中表单的切换
【发布时间】:2019-12-28 05:40:08
【问题描述】:

我正在使用一个简单的表单:

HTML

<mat-card>
  <form (submit)="onAddBet(betForm)" #betForm="ngForm">
    <mat-form-field>
      <textarea #description="ngModel" matInput rows="6" placeholder="Description" name="description" ngModel
        required></textarea>
      <mat-error *ngIf="description.invalid">Please enter a Bet Description</mat-error>
    </mat-form-field>
    <mat-slide-toggle #privacy="ngModel" name="privacy" ngModel>Private</mat-slide-toggle>
    <mat-slide-toggle #comments="ngModel" name="comments" ngModel>Allow comments</mat-slide-toggle>
    <button mat-raised-button color="primary" type="submit">
      CREATE
    </button>
  </form>
</mat-card>

如果我在不触及表单的任何字段的情况下按提交,我会按预期将所有字段都留空,但我想获得而不是表单的状态,这意味着所有字段都为 "",但在字段“privacy”和“cmets”为 false(布尔值)(切换的默认外观未标记)。

我知道这可以通过 Typescript 从组件中的方法轻松完成:

打字稿

onAddBet(form: NgForm) {
    if (!form.value.privacy) {
      form.value.privacy = false;
      console.log(form.value);
    } else console.log(form.value);
    if (form.invalid) return;
    form.resetForm();
  }

但我想知道是否有任何 HTML 属性来运行相同的代码,避免使用 Typescript

我该怎么做?

【问题讨论】:

  • 能否也提供您的组件代码?
  • 当然。实际上,为了得到我所期待的确切答案,我已经改写了我的问题。

标签: html angular angular-material toggle


【解决方案1】:

您可以在 HTML 中使用带有单向绑定的 ngModel 来初始化您的 ngModel

<mat-slide-toggle #privacy="ngModel" name="privacy" [ngModel]="false">Private</mat-slide-toggle>
<mat-slide-toggle #comments="ngModel" name="comments" [ngModel]="false">Allow comments</mat-slide-toggle>

然后在你的组件中

onAddBet(form: NgForm) {
    console.log(form.value);
    if (form.invalid) return;
    form.resetForm();
}

【讨论】:

    【解决方案2】:

    根据slide-toggle 的文档,您可以在 HTML 中使用 [checked]="checked"。

    【讨论】:

    • [checked] 在使用ngModel 时不设置滑动切换
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多