【问题标题】:How can I add multiple select options based on some html?如何基于某些 html 添加多个选择选项?
【发布时间】:2018-08-30 15:02:30
【问题描述】:

基本上,我希望根据自定义 html 内容将(多个)选项标签动态添加到选择标签中。

我熟悉使用 ng-content 插入动态内容,这里的问题是动态内容需要分离出来并包裹在 mat-option 标签中。

我需要能够以某种方式接受完全自定义的 html,它可以是 div,或元素列表或其他任何内容,但它必须能够在选择选项中显示自定义 html(不仅仅是简单的字符串,如选项)..

下面是一个非常简单的示例,但请记住,我需要能够接受任何 html..(将其分解 / 或其他 / 然后在我的选择中显示该 html)

-

更糟糕的是,我认为可以作为后备的方法是使用包含多个 mat-options 的单个 ng-content..

<hxgn-common-dropdown [dynamicContent]="true" [(value)]="selected">
  <hxgn-common-dropdown-items>
    <mat-option [value]="1">
      <span class="example">I'm dynamic content = 1</span>
    </mat-option>
    <mat-option [value]="2">
      <span class="example>I'm dynamic content = 2</span>
    </mat-option>
  </hxgn-common-dropdown-items>
</hxgn-common-dropdown>

我希望这两个选项会出现在我的 mat-select 中:

<mat-select>
    <ng-content select="hxgn-common-dropdown-items"></ng-content>
</mat-select>

不幸的是,这只会呈现一个没有选项的 mat-select.. 我猜 mat-select 不适用于 ng-content?还是我错过了什么?

有没有更好的方法来做到这一点?

我基本上是在寻找任何方法来创建基于非自定义 html 的选择。这样,开发人员只需向我的控件提供一些 html,它就会自动呈现下拉列表。

添加了堆栈闪电战:https://stackblitz.com/edit/angular-mat-select-custom-options?file=src%2Fapp%2Fapp.component.html

【问题讨论】:

  • 你试过 ngFor 吗?
  • 您能解释一下吗?我熟悉 ngFor,但我不明白如何将自定义 html 内容分解为单独的选项标签
  • 它可能无法满足您的特定需求。 stackblitz.com/edit/angular-pudrt4
  • 您能否详细说明您要达到的目标?也许最终的输出......
  • 我希望最终结果是一个下拉列表,其中第一个选项是“我是动态内容 = 1”,第二个选项是“我是动态内容 = 2”(如果你看在我的代码示例中)

标签: angular typescript angular-material


【解决方案1】:

您可以这样做: 您可以创建一个指令,以便您可以Query 该指令。该指令不必有任何东西。 一旦你获得DirectivesList,你就可以像@ContentChildren(MyDirective, {read: ElementRef})一样阅读ElementRef

然后,您可以在自定义组件中渲染出您喜欢的 ElementRef。 设置一个示例 Stackblitz,我可以与您合作....

更新: 不是读取ElementRef,而是将内容投影元素包装在TemplateRef 中并从common-dropdown 查询common-dropdown-items。 然后你循环遍历common-dropdown-items TemplateRef作为mat-option的内容。

参考这个 stackblitz 示例https://stackblitz.com/edit/angular-8dibtq

【讨论】:

  • 这是如何启动的:stackblitz.com/edit/…
  • 我觉得它是这样的:但我不能完全理解它:
  • 怎么样? stackblitz.com/edit/… 我需要重做您的装备,因为引导下拉菜单,因为入口组件不起作用。此外,mat-option 需要直接在 mat-select 内 - 否则不会选择
  • 太完美了!!如果你想用一些代码更新你的答案,我会接受它并给你赏金!谢谢!!!
【解决方案2】:

您是否尝试过使用JQuery Accordion

【讨论】:

  • 谢谢,但我想坚持使用 angular 和 angular-material 工具包。我只需要一些关于分解动态内容的最设计方法的指导我不需要任何其他工具包或库
猜你喜欢
  • 2018-09-16
  • 2019-12-22
  • 2017-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多