gpt4 book ai didi

typescript - Angular2 中的 ng-switch

转载 作者:太空狗 更新时间:2023-10-29 17:05:10 25 4
gpt4 key购买 nike

我正在玩 angular 2(目前版本为 alpha 26)。 ng-forng-if例如工作正常。但是我确实有问题 ng-switch .我只是无法让它工作,即没有打印任何东西。似乎整个模板都被忽略了。

这是我的组件的代码,也可以在 github 上找到:

import {Item} from "js/types/item";
import {Component, View, NgFor, NgIf, NgSwitch} from "angular2/angular2";

@Component({
selector: "item-details",
properties: [
"item"
]
})
@View({
template: `<span>You selected {{item.name}},</span>
<span [ng-switch]="item.name">
<template [ng-switch-when]="'Bill'">
<span> who is often called Billy.</span>
</template>
<template [ng-switch-when]="'Bob'">
<span> who is often called Bobby.</span>
</template>
<template [ng-switch-default]">
<span>who has no nickname.</span>
</template>
</span>
<div *ng-if="item.subItems">
<h2>Sub items:</h2>
<ul>
<li *ng-for="#subItem of item.subItems">{{subItem.name}}</li>
</ul>
</div>`,
directives: [NgFor, NgIf, NgSwitch]
})
export class ItemDetailsComponent {
item:Item;
}

基本上这是一个简单的组件,我向其中注入(inject)了一个具有 name 的项目。属性(property)。 name属性确实有一个值,我可以将其视为行 <span>You selected {{item.name}},</span>工作正常。

我不知道,为什么它不起作用。根据我的理解,一切都应该是正确的。我与 github 上的 Angular repo 进行了比较,unit tests

这些是我检查过的,我认为没问题:

  • NgSwitch通过 directives 导入和注入(inject)
  • 语法正确
  • item真的可用(但可能不在 NgSwitch 的上下文中?)

只是为了确定,我还尝试了一些微不足道的事情,比如下面的模板(切换硬编码字符串或数字):

<span [ng-switch]="'foo'">
<template [ng-switch-when]="'foo'">
<span> who is often called foo.</span>
</template>
<template [ng-switch-when]="'bar'">
<span> who is often called bar.</span>
</template>
</span>

这也不起作用,所以它一定是我做错的非常基本的东西。恐怕我在互联网上找不到任何示例或代码片段。任何帮助将不胜感激,提前致谢。

最佳答案

您需要导入 NgSwitchWhenNgSwitchDefault,将它们添加到导入语句中

关于typescript - Angular2 中的 ng-switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30724410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com