简体   繁体   English

我无法设置 html Angular 元素的属性

[英]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.我正在研究 Angular 的培训项目,像 2020 年这样的项目,但没有任何效果。 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:我有版本 11,教程使用 9。教程定义了一个变量,它改变了 html 元素的属性,在创建它时,我设置了初始值:

menuMode = 'push';

and here I pass it to html在这里我将它传递给 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.在组件 class 中,此行将创建一个名为menuMode的变量,其值为 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'此行将创建一个名为menuMode的变量,其类型为'over' | 'push' | 'slide' 'over' | 'push' | 'slide' 'over' | 'push' | 'slide' , but no value is assigned. 'over' | 'push' | 'slide' ,但没有赋值。 I believe the default state will be undefined:我相信默认的 state 将是未定义的:

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.我不确定您是否是创建ng-sidebar的人,因为它不是我认识的组件。 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.并且ng-sidebar内部的 mode 值必须是相同的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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