【问题标题】:Angular2. How can I use *ngFor for set "URL" in the tag "href" and set '{{theme.name}}' in the condition *ngIf?角2。如何使用 *ngFor 在标签“href”中设置“URL”并在条件 *ngIf 中设置“{{theme.name}}”?
【发布时间】:2017-03-06 06:46:32
【问题描述】:

我需要切换模板。 我有 12 个 css 文件需要动态加载

我有一个模板 html。例如(硬代码):

<div class="container">
    <link rel='stylesheet'   href="/app/switchTemplate/css/amelia/bootstrap.min.css" *ngIf="currentTheme.name === 'amelia'" />
</div>

当我使用 标记“href”时 它不起作用(动态)

<div class="container">
    <link rel='stylesheet'  *ngFor="let theme of themes"  href="{{theme.url}}" *ngIf="currentTheme.name === '{{theme.name}}'" />
</div>

如何使用 *ngFor 在标签“href”中设置“URL”并在条件 *ngIf 中设置“{{theme.name}}”?

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    一个元素上不能有多个结构指令。 您可以使用&lt;template&gt; 标记,但新的&lt;ng-container&gt; 元素更方便,因为它使用与普通元素上的结构指令相同的语法:

    <div class="container">
      <ng-container *ngFor="let theme of themes">
        <link rel='stylesheet'    href="{{theme.url}}" *ngIf="currentTheme.name === theme.name" />
      </ng-container>
    </div>
    

    &lt;template&gt;&lt;ng-container&gt; 元素仅由 Angular2 内部处理,从不添加到 DOM。

    【讨论】:

    • 感谢您的快速响应。
    • 但我有错误: zone.js:355 Unhandled Promise reject: Failed to load app/switchTemplate/templates/%7B%7Btheme.url%7D%7D ;区域: ;任务:Promise.then;值:无法加载 app/switchTemplate/templates/%7B%7Btheme.url%7D%7D undefined 我看到设置的 href 值不正确。我不明白,为什么没有设置正确的值?
    • 我在您的代码右侧看起来不够丰富。 *ngIf="currentTheme.name === '{{theme.name}}'" 应该是 *ngIf="currentTheme.name === 'theme.name'"。在属性上使用[]* 时,不要在绑定表达式中使用{{}}
    • 谢谢。当我删除代码右侧时 <ng-container theme of><link rel="stylesheet" href="%7B%7Btheme.url%7D%7D">container&gt; </ng-container> 无论如何,我有这个错误。我看到href等于:“app/switchTemplate/templates/%7B%7Btheme.url%7D%7D”
    • @Дмитрий Ерушенко 而且也不要在'theme.name' 表达式中使用''。似乎你需要使用属性绑定 hrefDomSanitizer plnkr.co/edit/deimCC3vqnUTdHErtPXC?p=preview
    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 2013-12-31
    • 1970-01-01
    • 2018-09-21
    • 1970-01-01
    • 2017-01-13
    • 2021-06-02
    • 2017-12-28
    相关资源
    最近更新 更多