user14828311
user14828311

Reputation:

I can't set the property of the html Angular element

I'm studying Angular on a training project, a project like and 2020, but nothing works. I have version 11, the tutorial uses 9. The tutorial defines a variable that changes the property of the html element, when creating it, I set the initial value:

menuMode = 'push';

and here I pass it to html

<ng-sidebar
    [mode]="menuMode"
>

The compiler throws an error:

error TS2322: Type 'string' is not assignable to type '"over" | "push" | "slide"'

If you declare a variable like this:

menuMode: 'over' | 'push' | 'slide';

then the compiler skips, but this is somehow not correct, and if another property appears tomorrow

Upvotes: 0

Views: 68

Answers (1)

JeffryHouser
JeffryHouser

Reputation: 39408

There are some differences I notice in your sample code. In a component class, this line will create a variable named menuMode with the value push. No type is explicitly defined, but string will be inferred:

menuMode = 'push';

This line will create a variable named menuMode with the type of 'over' | 'push' | 'slide', but no value is assigned. I believe the default state will be undefined:

menuMode: 'over' | 'push' | 'slide';

I suspect if you combine the two you'll get what you're after.

menuMode: 'over' | 'push' | 'slide' = 'push';

I'm not sure if you are the one who create ng-sidebar, because it is not a component I recognize. Personally I try to avoid union types like this. Since you have a controlled vocabulary I would define this as an enum:

export enum MENU_MODES {
  OVER: 'over',
  PUSH: 'push',
  SLIDE: 'slide'
}

You'd set your menu mode value, like this:

menuMode: MENU_MODES  = MENU_MODES.PUSH;

And the mode value inside of ng-sidebar would have to be of the same type.

Upvotes: 1

Related Questions