我想使用ngSwitch有条件地呈现某些内容,但我希望该内容成为要呈现给DOM的唯一内容。我将举例说明。

这是我目前拥有的:

<div [ngSwitch]="thing.name">
    <template ngSwitchWhen="foo">
        <div>FOOOOOO</div>
    </template>
    <template ngSwitchWhen="bar">
        <div>BARRRR</div>
    </template>
    <template ngSwitchWhen="cat">
        <div>CAT</div>
    </template>¯
    <template ngSwitchWhen="dog">
        <div>DOG</div>
    </template>
</div>

我想将父元素从<div>更改为<template>,以便实际上仅将最内部的元素插入DOM。我怀疑这可能是可能的,因为我知道您可以使用ngFor做类似的事情,即:
<template ngFor [ngForOf]="things" let-thing="$implicit">
但是,我无法弄清楚如何使它在ngSwitch上工作

最佳答案

自最终版本以来,现在支持该功能。以下代码可以应用于您的示例:

<div *ngSwitch="thing.name">
    <template [ngSwitchCase]="foo">
        <div>FOOOOOO</div>
    </template>
    <template [ngSwitchCase]="bar">
        <div>BARRRR</div>
    </template>
    <template [ngSwitchCase]="cat">
        <div>CAT</div>
    </template>¯
    <template [ngSwitchCase]="dog">
        <div>DOG</div>
    </template>
</div>

有关更多信息,请参见documentation

10-06 04:42