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

Дми*_*нко 3 ngfor angular

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

我有一个模板html。例如它的工作原理(硬编码):

<div class="container">
    <link rel='stylesheet'   href="/app/switchTemplate/css/amelia/bootstrap.min.css" *ngIf="currentTheme.name === 'amelia'" />
</div>
Run Code Online (Sandbox Code Playgroud)

当我使用 <*ngFor="let theme of themes"> 标记“href”时,它不起作用(动态)

<div class="container">
    <link rel='stylesheet'  *ngFor="let theme of themes"  href="{{theme.url}}" *ngIf="currentTheme.name === '{{theme.name}}'" />
</div>
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 5

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

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

<template><ng-container>元件仅由Angular2内部处理并从未添加到DOM。

  • @Дмитрий Ерушенко 并且不要在`'theme.name'` 表达式中使用`''`。似乎您需要将 `href` 的属性绑定与 `DomSanitizer` 一起使用 https://plnkr.co/edit/deimCC3vqnUTdHERtPXC?p=preview (2认同)