zoukankan      html  css  js  c++  java
  • [Angular] Configurable Angular Components

    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).

  • 相关阅读:
    Python Requests-学习笔记(9)-错误与异常
    .NET C# 创建WebService服务简单的例子
    10个免费开源的JS音乐播放器插件
    7款高颜值HTML5播放器:让你的音乐有声有色
    Asp.net基于session实现购物车的方法
    ASP.NET用GridView控件实现购物车功能
    jquery鼠标跟随流体吸引特效
    jquery鼠标跟随特效
    JQUERY互动星空粒子背景效果
    jQuery插件库常用前端库引用地址
  • 原文地址:https://www.cnblogs.com/Answer1215/p/7097024.html
Copyright © 2011-2022 走看看