[Angular] Configurable Angular Components - Content Projection and Input Templates

We are going to have a modal component:

<au-modal >

</au-modal>

And we can pass default modal body by content projection:

<au-modal >
    <modal-body></modaö-body>
</au-modal>

So 'modal-body' will be shown by default. 

 

Now we want to modal body can be configurable. We can choose to pass in a new template thought @Input, if template was passed in then use template instead of 'modal-body':

<ng-template #newModalBody>
    <!-- template goes here-->
</ng-template>

<au-modal [body]="newModalBody">
    <au-modal-body></au-modal-body>
</au-modal>

To do that, we defined a 'ng-template' and mark it as 'newModalBody' templateRef. It contians ours new template. And we can pass the template thought @Input.

 

So in the au-modal, it defines:

import {Component, Input, OnInit, TemplateRef} from '@angular/core';

@Component({
  selector: 'au-modal',
  templateUrl: './au-modal.component.html',
  styleUrls: ['./au-modal.component.scss']
})
export class AuModalComponent implements OnInit {

  @Input() body: TemplateRef<any>;
  constructor() { }

  ngOnInit() {
  }

}

 

In the component html, we need to check whether we pass in the template or not, if new template is present then we use it, otherwise, we fallback to default content projection:

<div class="modal-overlay">

  <div class="modal-body">

    <ng-container *ngIf="body else projectionBody">
      <ng-container *ngTemplateOutlet="body"></ng-container>
    </ng-container>

    <ng-template #projectionBody>
      <ng-content></ng-content>
    </ng-template>

  </div>

</div>

The reason here we use two ng-container is because, for one ng-container can only have one structure directive (*ngIf or *ngTeplateOutlet).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值