Angular - Building form based on user input Angular - Building form based on user input angular angular

Angular - Building form based on user input


I'd suggest creating a component for each sub-form and then *ngIf them based on the selected option, like so:

<!-- 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>

If you already have something holding your Type selection, you can bind that to the *ngIfs instead. If not, create a field in your controller class and hold the selected type in there.

// component.tspublic type: number | null = null;public onTypeChosen(type: number, row): void {  this.type = type;}

If your sub-forms have parts that are re-usable (or are basically the same, sans configuration), it's generally a good practice to extract the re-usable code into components in and of themselves and compose them together.

Hope this helps a little :-)


To Add the options dynamically, angular provide ( *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> 

in your controller .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);}