ami*_*ros 8 html dom angular angular-forms
我正在构建一个应该是动态的Web表单.
当用户从列表中选择选项时,将根据其输入生成下一个表单输入.
例如:
<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>
Run Code Online (Sandbox Code Playgroud)
如果他选择类型'治疗',他会获得另一个选择输入,其中包含一些其他输入的选项,如果他选择不同的类型,他会获得不同的选项和其他输入.
我知道我需要动态生成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>
Run Code Online (Sandbox Code Playgroud)
如果您已经拥有类型选择的东西,则可以将其绑定到*ngIfs.如果没有,请在控制器类中创建一个字段并在其中保存所选类型.
// component.ts
public type: number | null = null;
public onTypeChosen(type: number, row): void {
this.type = type;
}
Run Code Online (Sandbox Code Playgroud)
如果您的子表单具有可重用的部分(或基本相同,无配置),通常将可重用代码提取到组件中并将它们组合在一起是一种很好的做法.
希望这有所帮助 :-)
要动态添加选项,角度提供 ( *ngFor)。
<mat-form-field>
<mat-select placeholder="Type" [(ngModel)]="row.Type" (change)="TypeChosen(row.Type, row)" *ngFor="let option of options; let i = index">
<mat-option (click)="updateOptions(option)" [value]="{{i}}">option.text</mat-option>
</mat-select>
</mat-form-field>
Run Code Online (Sandbox Code Playgroud)
在你的控制器.ts中
private options = [];
private initOptions(){
this.options = [
{text:'Treatment' , possibleOptionsRelates:[text:'possible1']},
{text:'Travel' , possibleOptionsRelates:[text:'possible12']},
{text:'Medication' , possibleOptionsRelates:[text:'possible13']}];
}
private updateOptions(option){
this.options.push(...option.possibleOptionsRelates);
}
Run Code Online (Sandbox Code Playgroud)