0%

angular-ng-content

What is ng-content in Angular?

Angular’s ng-content element is used to project content into a component.

通常我们定义一个组件时,都会在某个html模板中使用组件对应的selector来引用组件。例如:

1
<app-my-component></app-my-component>

注意观察以上组件的html结构,app-my-component标签中间是没有内容的。这种组件的特点是静态的,无法动态插入内容。如果我们需要动态的更改组件中的某个部分,那就需要用到ng-content了。

考虑下面的例子,假设我们有一个Card组件,我们希望Card组件的内容是动态的,可以根据不同的需求插入不同的内容。但是我们又希望Card的Header和Footer是固定的,不会变化。这个需求就可以用ng-content来实现。

1
2
3
<header>Card Header</header>
<ng-content></ng-content>
<footer>Card Footer</footer>

假设我们要创建一个内容为Hello, world!的Card组件,我们可以这样写:

1
2
3
<app-card>
<p>Hello, world!</p>
</app-card>

Angular最终会将<p>Hello, world!</p>插入到<ng-content></ng-content>标签的位置,渲染结果如下:

1
2
3
<header>Card Header</header>
<p>Hello, world!</p>
<footer>Card Footer</footer>

这就是ng-content的作用。

总结

使用ng-content可以实现动态插入内容到组件中,使得组件更加灵活。

  1. 固定不变的内容直接书写到组件模板中。
  2. 动态的内容使用ng-content来插入。