如何在指令中使用 ng-content

How to use ng-content within a directive

如何使用 angular @Directive 创建自定义按钮元素,就像 angular 对 mat-button 所做的一样?

比方说,我在写

<button mat-button>Basic</button>

并且angular这样显示

<button mat-button="" class="mat-focus-indicator mat-button mat-button-base">
  <span class="mat-button-wrapper">Basic</span>
</button>

我怎样才能做到这一点?

<button custom-button>Basic</button>

Angular material 使用 @Componentmat-button,因为(众多)选择器是 button[mat-button]。所以它是一个组件,而不是一个指令(虽然一个组件扩展了指令,但你明白了)

您可以查看 here 他们是如何做到的。

这是他们使用的模板的一部分:

<span class="mat-button-wrapper"><ng-content></ng-content></span>