0

i have a dropdown and i have true or false value .

        <mat-form-field class="mat-form-field-fluid" appearance="outline">
                    <mat-label>{{ 'GENERAL.SEE_STATUS'| translate }}</mat-label>
                    <mat-select formControlName="hasSeen">
                        <mat-option value="" selected>
                            {{ 'GENERAL.ALL' | translate }}</mat-option>

                        <mat-option value=true>
                            {{'NOTIFYCATION.SEEN' | translate}}
                        </mat-option>
                        <mat-option value=false>
                            {{'NOTIFYCATION.NOT_SEEN' | translate}}
                        </mat-option>
                    </mat-select>
                </mat-form-field>

and i need to fill the model by the dropdown value:

loadFilters(): void {

    const model = {} as SearchModel;
    model.hasSeen = <boolean>this.filterFormGroup.get('hasSeen').value;

    this.notificationService.updateFilter(model);
}

but when i console the model it have a string value like this "true" but i need this value true .

this is my model :

export interface SearchModel {
 hasSeen: boolean;
}

how can i convert strign to boolean ????

Nicholas K
  • 15,148
  • 7
  • 31
  • 57

1 Answers1

0

The problem

In your example, you are simply casting the value to a given type rather than converting the value.

model.hasSeen = <boolean>this.filterFormGroup.get('hasSeen').value;

All this does is tell typescript that you want to treat the string as a boolean. It will still be a string value afterwards, which is what you are seeing.

When it gets compiled to javascript, it is effectively the same as writing

model.hasSeen = this.filterFormGroup.get('hasSeen').value;

The solution

To solve a javascript problem, we must come up with a javascript solution. How about checking the string value matches the string representation of true?

model.hasSeen = this.filterFormGroup.get('hasSeen').value === 'true';
Kurt Hamilton
  • 12,490
  • 1
  • 24
  • 40