Angular material form input casts type to string if input type is set from a variable

Viewed 1110

I am dynamically creating a table with the ability to filter based on inputs in the column headers. I'm having an issue where the data type returned from the input is cast to a string, regardless of the type of the input, if the input type was set from a variable. So in my template, if i'm iterating over an array of class column and declare my input as:
<input matInput [type]="column.dataType" [formControl]="this.formGroup.controls[key]">, where column.dataType === 'number'
The form input returns to the component as a string. But if i declare it as:
<input matInput [type]="number" [formControl]="this.formGroup.controls[key]">,
it returns a number.

Here's a pared down, unrunnable snippet, for context. Why does the input value change if i set the type from a variable vs hardcoding?

@Component({
    selector: 'app-filter-table',
    templateUrl: './filter-table.component.html',
    styleUrls: ['./filter-table.component.scss']
})
export class FilterTableComponent<T> implements OnInit{
    @Input() displayColumns?: ColumnDefinition[];

    columnNames = new Array<string>();
    formGroup: FormGroup;

    ngOnInit() {
        const groupControls = {};

        this.displayColumns.forEach(columnDef => {
            const control = new FormControl();
            groupControls[columnDef.name] = control;
            this.columnNames.push(columnDef.name);
        });
        this.formGroup = new FormGroup(groupControls);
    }
    
    getControl(key: string): AbstractControl {
        return this.formGroup.controls[key];
    }

    getForm() {
        return this.formGroup.value;
    }
}
<form [formGroup]>
    <mat-table [dataSource]="dataSource" class="mat-elevation-z1">
        <div *ngFor="let column of displayColumns">
            <ng-container [matColumnDef]="column.name">
                <mat-header-cell *matHeaderCellDef>
                    <mat-form-field class="headerInput">
                         <!-- vvv-if [type]="column.type", getForm() returns a form with strings, if [type]="number", it returns numbers -->
                        <input matInput [type]="column.type" [placeholder]="column.label"
                            [formControl]="getControl(column.name)">
                    </mat-form-field>
                </mat-header-cell>
                <mat-cell *matCellDef="let row"> {{row[column.name]}} </mat-cell>
            </ng-container>
        </div>
        <mat-header-row *matHeaderRowDef="columnNames"></mat-header-row>
        <mat-row *matRowDef="let row; columns: columnNames"></mat-row>
    </mat-table>
</form>

0 Answers
Related