简体   繁体   中英

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

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' 'over' | 'push' | 'slide' '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM