【问题标题】:Angular - two the same ng-template with component in one HTML file (How to make reference, not copy)Angular - 两个相同的 ng-template 与一个 HTML 文件中的组件(如何参考,而不是复制)
【发布时间】:2020-12-05 21:13:18
【问题描述】:

我有以下问题:我使用 Angular 创建了一个 Web 应用程序。我正在制作一个包含多个字段的搜索表单。我已经把它作为一个组件准备好了。代码如下:

<ng-template #filter>
  <app-articles-filter #articlesFilterDesktop
                       (onFilterFormSubmit)="submitFilterForm()"
                       [categories]="categories"></app-articles-filter>
</ng-template>

要将此代码放在页面上,我使用的是ng-container&lt;ng-container *ngTemplateOutlet = "filter"&gt; &lt;/ng-container&gt;。默认情况下,搜索表单位于页面顶部。我还想这样做,当用户调整窗口(移动设备)的大小时,一个按钮会出现在搜索表单的位置。单击此按钮后,将出现带有此搜索表单的模式窗口。模态窗口代码(我用的是Bootstrap):

<div class="modal fade" id="filterArticlesModal" tabindex="-1" role="dialog" aria-labelledby="filterArticlesModalTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <ng-container *ngTemplateOutlet="filter"></ng-container>
      </div>
    </div>
  </div>
</div>

在一个 HTML 文件中使用 ng-template 两次使用相同的组件,我在控制台中收到警告: “找到 2 个具有非唯一 id 的元素 [此处重复 id]:[此处搜索表单中的 html]”。

在搜索表单中填写的字段不会在模式视图中自动填写。 (当我在页面上完成表单时,缩小浏览器窗口并打开模态窗口。模态窗口中有空字段,反之亦然)。据我了解,Angular 只是粘贴代码,仅此而已。是否可以以某种方式将此代码片段(我的搜索表单组件)视为一个引用而不是副本?

【问题讨论】:

    标签: html angular bootstrap-4


    【解决方案1】:

    编辑:

    我不确定重复 ID 的惨败。您可以删除 id 并退出类,或者将组件中的一些属性添加到您可以控制的 ID 中:id="searchBar{{foo}}"?

    在搜索之间切换时解决数据一致性问题绝对可以做到。 如果您想让搜索值充当单例,我建议将该值放在服务中,并从组件中引用它。这可以通过几种不同的方式完成,并且需要考虑一件事:

    您是否希望在导航到/从页面后继续搜索?如果是,则保持存储搜索全局的服务,如果不在提供者中定义它:[] 包含这些搜索组件的组件的属性(这样每次组件被销毁时它都会被删除)

    【讨论】:

    • 但这就是我刚刚所做的。问题是它只是从 ng-template 复制代码并将其粘贴到 ng-container * ngTemplateOutlet = "filter" 中。所以我有关于过滤表单中使用的重复 id 的警告。
    • 很抱歉这个答案,看起来不够努力。这是一个棘手的问题,我希望编辑后的答案能帮助更多
    猜你喜欢
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-01
    • 2019-02-04
    • 2020-12-28
    • 1970-01-01
    相关资源
    最近更新 更多