haizlin / fe-interview

前端面试每日 3+1,以面试题来驱动学习,提倡每日学习与思考,每天进步一点!每天早上5点纯手工发布面试题(死磕自己,愉悦大家),6000+道前端面试题全面覆盖,HTML/CSS/JavaScript/Vue/React/Nodejs/TypeScript/ECMAScritpt/Webpack/Jquery/小程序/软技能……
http://www.h-camel.com
MIT License
25.02k stars 3.24k forks source link

[angular] 第1882天 请说说在Angular中ng-content和select的了解 #5844

Open haizhilin2013 opened 3 weeks ago

haizhilin2013 commented 3 weeks ago

第1882天 请说说在Angular中ng-content和select的了解

3+1官网

我也要出题

llccing commented 3 days ago

在Angular中,ng-contentselect 是用于内容投影(Content Projection)的重要工具。内容投影允许你将父组件的内容插入到子组件的特定位置,从而实现更灵活和可重用的组件设计。

ng-content

ng-content 是 Angular 提供的一种指令,用于在子组件模板中定义插槽(slot),这些插槽可以被父组件的内容填充。基本用法如下:

基本用法

假设有一个子组件 child.component.html

<div>
  <h2>Child Component</h2>
  <ng-content></ng-content>
</div>

在父组件中使用这个子组件:

<app-child>
  <p>This is projected content from parent.</p>
</app-child>

结果是,父组件的内容会被投影到 ng-content 所在的位置:

<div>
  <h2>Child Component</h2>
  <p>This is projected content from parent.</p>
</div>

select 属性

select 属性用于选择特定的内容投影到指定的 ng-content 插槽中。通过使用 select 属性,你可以在子组件中定义多个投影点,并根据需要将不同的内容投影到不同的位置。

多个投影点

假设有一个子组件 child.component.html,其中有多个投影点:

<div>
  <h2>Child Component</h2>
  <ng-content select=".header"></ng-content>
  <ng-content select=".body"></ng-content>
  <ng-content select=".footer"></ng-content>
</div>

在父组件中使用这个子组件:

<app-child>
  <div class="header">Header Content</div>
  <div class="body">Body Content</div>
  <div class="footer">Footer Content</div>
</app-child>

结果是,不同的内容会被投影到对应的 ng-content 插槽中:

<div>
  <h2>Child Component</h2>
  <div class="header">Header Content</div>
  <div class="body">Body Content</div>
  <div class="footer">Footer Content</div>
</div>

总结

通过使用 ng-contentselect,你可以创建更加灵活和可重用的组件,提升应用的模块化和可维护性。