【问题标题】:Angular - show projected content in different locations via conditional logicAngular - 通过条件逻辑在不同位置显示投影内容
【发布时间】:2022-08-08 12:05:36
【问题描述】:

我正在 Angular 中构建一个 Header 组件,并希望根据输入 inputTwoRows 是否已设置为 true/false 在 DOM 结构中的不同位置显示导航。导航通过内容投影添加到 Header\ 的模板 - ng-content。我试图在模板中的不同位置将 2 ng-content 包装在 ng-templates 中,并添加 ngIf 以有条件地显示它们。然而,这些模板试图显示相同的投影内容。正如您将在演示问题的 Stackblitz 链接中看到的那样,如果 [twoRows]=\"true\"c-header 上,则仅显示第一个 ng-content。以下是header.component.html 的代码:

<header>
  <div>logo</div>
  <ng-template [ngIf]=\"inputTwoRows\">
    <p>Two Rows</p>
    <ng-content select=\"c-header-nav\"></ng-content>
  </ng-template>
  <div>utils</div>
  <ng-template [ngIf]=\"!inputTwoRows\">
    <p>One Row</p>
    <ng-content select=\"c-header-nav\"></ng-content>
  </ng-template>
</header>

如果ng-template 中的内容不是ng-content,则此逻辑可以正常工作。有没有办法以某种方式实现我最初的目标?

https://stackblitz.com/edit/angular-ivy-xfr7hs?file=src/app/components/header/header.component.html

谢谢

詹姆士

    标签: angular angular-content-projection


    【解决方案1】:

    我最终定义了一个包裹在&lt;ng-template&gt; 中的&lt;ng-content&gt;。然后我将&lt;ng-containers&gt; 放在DOM 中我需要它们的位置。外部&lt;ng-containers&gt; 处理条件逻辑,内部&lt;ng-containers&gt; 引用&lt;ng-template&gt;(如果需要):

    <header>
      <div>logo</div>
      <ng-container *ngIf="!twoRows">
        <ng-container *ngTemplateOutlet="headerNavTemplate"></ng-container>
      </ng-container>
      <div>utils</div>
      <ng-container *ngIf="twoRows">
          <ng-container *ngTemplateOutlet="headerNavTemplate"></ng-container>
      </ng-container>
      <ng-template #headerNavTemplate>
        <ng-content select="c-header-nav"></ng-content>
      </ng-template>
    </header>

    【讨论】:

      【解决方案2】:

      这是因为 ng-content 发生在构建时。 在宿主组件实例化的时候被实例化,也意味着Angular编译器在编译代码时会创建规则和相关的JS代码。没有运行时会影响以后的行为。 更新组件时它不会更改。

      【讨论】:

      • 好的,谢谢,那我该怎么做才能解决这个问题?
      • 你可以使用 ngProjectAs="selector-name" 或者给组件一个特殊的标识符。问题是你用相同的名字命名了你的 ng-content 选择器,所以第一个被实例化的 ng-content 发生了。以下是解决问题的链接:stackblitz.com/edit/…
      • 感谢您的帮助,但我不希望应用程序中有多个 Header Nav 组件实例。我正在构建的组件是用于 Angular 组件库的,我不希望用户为了解决这个问题而必须定义多个导航。我现在已经设法解决了这个问题。很快就会发布我的解决方案。
      • 你可以尝试做一些类似门户的事情:stackblitz.com/edit/angular-ivy-ysx6kr?file=src/app/…
      猜你喜欢
      • 1970-01-01
      • 2018-01-30
      • 2023-03-23
      • 1970-01-01
      • 2020-03-21
      • 2023-04-01
      • 2019-03-23
      • 1970-01-01
      • 2017-01-14
      相关资源
      最近更新 更多