[Angular] Remove divs to Preserve Style and Layout with ng-container in Angular

本文介绍Angular中ng-container元素的应用场景,通过实例展示如何使用ng-container来避免DOM中不必要的div标签,优化内容投影机制。

The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.

 

When we using Content Projection in a DUMP component:

<div class="card" style="width: 18rem;">
  <ng-content select=".heading"> </ng-content>
  <div class="card-body">
   <ng-content select=".body"> </ng-content>
  </div>
</div>

We are using <ng-content> here to get projected element from the SMAR component:

<app-card>
  <div class="heading"> <!-- add a extra div with class selector to wrap the elements -->
    <img class="card-img-top" src="https://picsum.photos/g/200/300" alt="Card image cap">
  </div>
  <div class="body"> <!-- add a extra div with class selector to wrap the elements -->
    <h5 class="card-title">Card Title</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </div>
</app-card>

 

It ends up we have a extra div in the DOM, to remove that extra div, we just need to replace 'div' with 'ng.container':

<app-card>
  <ng-container class="heading">
    <img class="card-img-top" src="https://picsum.photos/g/200/300" alt="Card image cap">
  </ng-container>
  <ng-container class="body">
    <h5 class="card-title">Card Title</h5>
    <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
    <a href="#" class="btn btn-primary">Go somewhere</a>
  </ng-container>
</app-card>

 

转载于:https://www.cnblogs.com/Answer1215/p/9221430.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值