浅谈ng-content,ng-template与ng-container的区别

1.ng-content
ng-content的作用是内容投影,主要用法是在父组件中将html投影到子组件中,具体写法如下
父组件html

<app-zippy-basic>
  <p>Is content projection cool?</p>
</app-zippy-basic>

子组件ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-zippy-basic',
  template: `
    <h2>Single-slot content projection</h2>
    <ng-content></ng-content>
  `
})
export class ZippyBasicComponent {}

上面的情况就是将父组件html中的p标签直接放入子组件中需要投影的位置,即ng-content所在位置,此外,ng-content投影还提供好几种选择器
1.标签选择器

<ng-content select="div"></ng-content>

例如上述情况此投影区域只会投影父组件中子组件标签包裹的div标签内容,多个相同类名会被一起渲染,其他标签同理
2.类选择器

<ng-content select=".test"></ng-content>

例如上述情况此投影区域只会投影父组件中子组件标签包裹的类名为test的内容,多个相同类名会被一起渲染
3.id选择器

<ng-content select="#test"></ng-content>

例如上述情况此投影区域只会投影父组件中子组件标签包裹的id为test的内容
4.key选择器
子组件

<ng-content select=[question]></ng-content>

父组件

<app-zippy-multislot>
  <p question>Is content projection cool?</p>
</app-zippy-multislot>

2.ng-template
ng-template是一个模板,它不会直接显示在html页面上,而是需要一个判断条件,通常情况下的用法

<div *ngIf="condition else elseTemplate">
   <div>true content</div>
</div>
<ng-template #elseTemplate>
    <div>false content</div>
</ng-template>

也可以直接放在html中,通过注入ViewContainerRef(其为view元素的引用),调用其内置api createEmbeddedView在视图加载完后将模板添加至dom元素中
html

<ng-template #demoTemplate>
   <div>demo content</div>
</ng-template>

ts

  @ViewChild('demoTemplate') demoRef: TemplateRef<any>;
  constructor(private viewContainerRef: ViewContainerRef) {}

  ngAfterViewInit() {
    this.viewContainerRef.createEmbeddedView(this.demoRef);
  }

3.ng-container
ng-container在通常情况下是一个tag,不改变样式和布局,甚至不生成元素标签

html

<ng-container>
   <div>demo content</div>
</ng-container>

dom
在这里插入图片描述
当需要元素包裹某些元素但又不出现多余元素的情况下,可以使用ng-container进行包裹
对比如下
第一种情况

<div *ngFor="let i of [5,10,15]">
  <div *ngIf="i > 10">
    <div>{{i}}</div>
  </div>
</div>

dom
在这里插入图片描述
第二种情况

<div *ngFor="let i of [5,10,15]">
  <ng-container *ngIf="i > 10">
    <div>{{i}}</div>
  </ng-container>
</div>

dom
在这里插入图片描述
第三种情况

<ng-container *ngFor="let i of [5,10,15]">
  <ng-container *ngIf="i > 10">
    <div>{{i}}</div>
  </ng-container>
</ng-container>

dom
在这里插入图片描述
对比一下就很好理解,在ng-container上使用功能性指令,不仅能起到作用,在dom加载时也不会渲染多余元素,但是也需适应当前开发情况,并不指越多使用就更好

感谢指正

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值