基本上我想基于自定义的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>
不幸的是,这只是使用NO选项呈现mat-select ..我猜mat-select不适用于ng-content?或者我错过了什么?
有一个更好的方法吗?
我基本上寻找任何方法来创建一个基于自定义html的选择。这样开发人员可以只为我的控件提供一些html,它会自动渲染下拉列表。
添加了stackblitz:https://stackblitz.com/edit/angular-mat-select-custom-options?file=src%2Fapp%2Fapp.component.html
这是你如何做到这一点:你可以创建一个指令,以便你可以Query
指令。该指令不必有任何东西。一旦你获得了List
的Directives
,你就可以像ElementRef
一样阅读@ContentChildren(MyDirective, {read: ElementRef})
然后,您可以在自定义组件中渲染ElementRef。设置一个示例Stackblitz,我可以与你合作....
更新:不是阅读ElementRef
,而是将内容投影元素包装在TemplateRef
中,并从common-dropdown-items
查询common-dropdown
。然后你循环通过common-dropdown-items TemplateRef
作为mat-option
的内容。
请参阅这个stackblitz示例https://stackblitz.com/edit/angular-8dibtq
你尝试过使用JQuery Accordion吗?