[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).
相关文章
- 一个 Angular 开发人员对腾讯 Cloud Studio 使用后的体验报告
- Angular 面试题汇总2-Component/Service (Angular v8+)
- 关于 Angular Universal 应用执行时需要 Browser API 的问题
- Angular 应用开发里使用 ForRoot 解决 Lazy Loaded Module 里单例行为丢失的问题
- 【Angular教程】-内容投影u002F@ContentChildu002F@ViewChild
- Angular 项目多国语言设置
- Angular 应用里 ng-package.json 文件的作用是什么?
- Angular 应用 tsconfig.json 文件里的 typeRoots 属性讲解
- 关于 Angular 应用的 Bootstrap 过程
- 基于 Spartacus 的 Angular Storefront 性能优化建议
- Angular 依赖注入错误消息:ERROR Error NullInjectorError No provider for XX
- 深入探究Mysql中IN与AND逻辑运算的应用(mysql中in与and)
- Mysql中强大的AND运算符的使用方法探究(mysql中and的使用)
- MySQL中的AND和OR使用逻辑运算符优化查询语句(mysql中and与or)
- 使用angular写一个helloworld