【问题标题】:Angular 8 - *ngIf and mat-checkbox not workingAngular 8 - *ngIf 和 mat-checkbox 不起作用
【发布时间】:2019-11-25 06:10:02
【问题描述】:

我在使用 Angular Material Checkbox 时遇到问题,我认为这是一件相对简单的事情,但由于某种原因,我无法让它工作。

我有一个 div,我只想在选中 mat-checkbox 时显示它,但它似乎不想与 *ngIf 一起使用,即使我在这里找到了它的一个示例:https://stackblitz.com/edit/angular-mat-checked?file=app%2Fcheckbox-overview-example.html

我尝试将非常相似的代码应用到我的项目中,但它似乎不想工作,我尝试过的其他任何事情也没有。

        <mat-checkbox [(ngModel)]="checked" [checked]="false">
          I agree to {{clientName}} storing my details.
          <a href="#" target="_blank">View full terms & conditions</a>
        </mat-checkbox>

        <div *ngIf="checked" id="contactOptionsGroup">
          <p>Stay updated with news, features, and offers related to {{clientName}}.</p>
          <mat-checkbox>Phone</mat-checkbox>
          <mat-checkbox>Email</mat-checkbox>
        </div>

似乎能够通过选中和取消选中来显示和隐藏这个 div 应该相对简单,但我似乎被难住了。我可能遗漏了一些完全明显的东西,但我看不出它可能是什么。

项目稍后也会有此功能的另一个实例,因此它们需要彼此独立工作。

如果有人有帮助或建议,我将永远感激不尽。

【问题讨论】:

  • 你可以在你的组件中定义值而不是在你的模板中,例如export class CheckboxOverviewExample { checked: boolean = true; },然后从模板中删除你的ngInit
  • 我想我们只是假设有一个 typescript 文件,所有内容都设置正确?还有错误吗?
  • 我不明白,你想要这样的东西吗? stackblitz.com/edit/angular-lhaikj?file=src/app/app.module.ts 这是角度 8 中的快速示例
  • 你在ts文件中定义checked了吗?如果没有将其定义为 false 并删除它:[checked]="false"

标签: angular checkbox angular-material angular-ng-if


【解决方案1】:

您不需要在组件中定义变量。您也可以参考复选框

<mat-checkbox #termsAndConditions>
          I agree to {{clientName}} storing my details.
          <a href="#" target="_blank">View full terms & conditions</a>
        </mat-checkbox>

        <div *ngIf="termsAndConditions.checked" id="contactOptionsGroup">
          <p>Stay updated with news, features, and offers related to {{clientName}}.</p>
          <mat-checkbox>Phone</mat-checkbox>
          <mat-checkbox>Email</mat-checkbox>
        </div>

【讨论】:

  • 你是一个绝对的英雄,这很完美。谢谢!
猜你喜欢
  • 2018-06-17
  • 2019-05-13
  • 2020-04-28
  • 2020-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-19
  • 1970-01-01
相关资源
最近更新 更多