Reputation: 25
I'm currently learning Angular9 with Material and I have here a sample form for raffle. User fills out raffle info, they select from dropdown how many prizes are in this raffle and who are the winners. I have a drop down value selected and I want the "Winner" row to generate as much rows as my drop down selected value. So if there are 3 Top Prizes, then there should be 3 Winner rows. How do I dynamically generate number of rows based on the value selected from drop down?
<mat-card class="example-card">
<form [formGroup]="minisForm" (ngSubmit)="onFormSubmit()">
<mat-form-field class="example-full-width">
<mat-label>Raffle ID</mat-label>
<input matInput placeholder="Mini ID" formControlName="miniId" [errorStateMatcher]="matcher">
<mat-error>
<span *ngIf="!minisForm.get('miniId').valid && minisForm.get('miniId').touched">Please enter Mini ID</span>
</mat-error>
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Host Name</mat-label>
<input matInput placeholder="Item Name" formControlName="hostName" [errorStateMatcher]="matcher">
<mat-error>
<span *ngIf="!minisForm.get('hostName').valid && minisForm.get('hostName').touched">Please enter Host Name</span>
</mat-error>
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Top prizes</mat-label>
<mat-select [formControl]="numberOfWinners">
<mat-option value="option">1</mat-option>
<mat-option value="option">2</mat-option>
<mat-option value="option">3</mat-option>
<mat-option value="option">4</mat-option>
<mat-option value="option">5</mat-option>
</mat-select>
<mat-error *ngIf="!minisForm.get('spots').valid">Please enter number of Winners</mat-error>
</mat-form-field>
<mat-form-field class="example-full-width">
<mat-label>Winner</mat-label>
<input matInput type="number" placeholder="Winner" formControlName="winner" [errorStateMatcher]="matcher">
<mat-error>
<span *ngIf="!minisForm.get('winner').valid && minisForm.get('winner').touched">Please enter Winner</span>
</mat-error>
</mat-form-field>
<div class="button-row">
<button type="submit" [disabled]="!minisForm.valid" mat-flat-button color="primary"><mat-icon>save</mat-icon></button>
</div>
</form>
</mat-card>
Upvotes: 0
Views: 1206
Reputation: 535
You could do something like this: https://stackblitz.com/edit/angular-ivy-ftizjs
I just catch the change event on the dropdown and get the value. Then I create an array of size equal to the dropdown value, filled with anything, just so I can iterate over it on *ngFor.
Then, use *ngFor to dynamically create your rows.
Hope it makes sense!
Upvotes: 1