Home > Software design >  How to Set default value in a loop of formControls in HTML?
How to Set default value in a loop of formControls in HTML?

Time:12-14

I have an array of input elements with formControl Directive. I have set the value of each element with value attribute, but it showing blank. If I set the value in ts file, the same value will be set in each and every element. So, how to differentiate the elements if I have to set value in ts?

Here is my code:

HTML code:

<ng-container matColumnDef="amount">
    <th mat-header-cell *matHeaderCellDef>Amount
        <button mat-icon-button (click)="onEditClick(datasource.data)">
            <mat-icon style="cursor: pointer;"  >edit</mat-icon>
        </button>
    </th>
    <td mat-cell *matCellDef="let row; let i=index;">
        <ng-container *ngIf="isActual">{{row.amount || "-- --"}}</ng-container>
            <mat-form-field *ngIf="isEditMonth"  appearance="outline">
                <input #elRef matInput type="text" [formControl]="amountField" (change)="onAmountChanged($event,row)" [value]="row.amount">
            </mat-form-field>
    </td>
</ng-container>

TS Code:

amountField = new FormControl();

CodePudding user response:

The default value of the select element can be set by using the ‘selected’ attribute on the required option. This is a boolean attribute. The option that is having the ‘selected’ attribute will be displayed by default on the dropdown list

CodePudding user response:

this.form.controls['amountField'].setValue("Value you want to be selected");

You can set the value by using this.

  • Related