html - Angular - 基于用户输入的构建表单

标签 html angular dom angular-forms

我正在构建一个应该是动态的网络表单。
当用户从列表中选择一个选项时,将根据他的输入生成下一个表单输入。
例如:

<mat-form-field>
     <mat-select placeholder="Type" [(ngModel)]="row.Type" (change)="TypeChosen(row.Type, row)">
         <mat-option [value]="0">Treatment</mat-option>
         <mat-option [value]="1">Travel</mat-option>
         <mat-option [value]="2">Medication</mat-option>
         <mat-option [value]="3">Equipment</mat-option>
     </mat-select>
</mat-form-field>

如果他选择“治疗”类型,他会得到另一个选择输入,其中包含一些选项和一些其他输入,如果他选择不同的类型,他会得到不同的选项和其他输入。

我知道我需要动态生成 HTML 内容,可能还需要一个动态组件。
以简单的方式执行此操作的最佳方法是什么?

最佳答案

我建议为每个子表单创建一个组件,然后根据所选选项创建一个 *ngIf,如下所示:

<!-- component.html -->

<mat-form-field>
  <mat-select placeholder="Type" [(ngModel)]="row.Type" (change)="onTypeChosen(row.Type, row)">
    <mat-option [value]="0">Treatment</mat-option>
    <mat-option [value]="1">Travel</mat-option>
    <mat-option [value]="2">Medication</mat-option>
    <mat-option [value]="3">Equipment</mat-option>
  </mat-select>
</mat-form-field>

<my-treatment-component *ngIf="type === 0" [someInput]="'some value'"></my-treatment-component>
<my-travel-component *ngIf="type === 1" [somethingElse]="true"></my-travel-component>
<my-medication-component *ngIf="type === 2" (someOutput)="onMedicationOutput($event)"></my-medication-component>
<my-equipment-component *ngIf="type === 3"></my-equipment-component>

如果您已经有一些东西来保存您的类型选择,您可以将它绑定(bind)到 *ngIf。如果没有,请在您的 Controller 类中创建一个字段并将所选类型保存在其中。

// component.ts

public type: number | null = null;

public onTypeChosen(type: number, row): void {
  this.type = type;
}

如果您的子表单具有可重复使用的部分(或基本相同,无配置),通常将可重复使用的代码提取到组件本身并组合在一起是一个很好的做法。

希望这对您有所帮助:-)

关于html - Angular - 基于用户输入的构建表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50832489/

相关文章:

javascript - 获取带有显示 block 的父元素

javascript - 如何动态添加带有文本框的表格行?

javascript - 如何放弃单击按钮时的表单更改?

javascript - Flickr API 加载图像

php - 在 Laravel 和 Angular 项目中分离 AngularJS Controller 文件

node.js - Angular7:无法设置{responseType: 'text'}

javascript - 移动设备上的导航栏表现异常,页脚也是如此[前端]

html - 在标题旁边 float 图像并对齐段落

HTML5跨域通信不起作用

angular - 如何在 Kubernetes 中使用 nginx 连接前端和后端