How to reuse template HTML block in Angular?

后端 未结 5 958
野趣味
野趣味 2020-12-23 09:28

Lets suppose we have html block in file:

Text

How can I reuse this html code below in the same file, I m

5条回答
  •  伪装坚强ぢ
    2020-12-23 10:02

    This can be done with help of a custom directive in a more standard way, you can find more details https://www.digitalocean.com/community/tutorials/angular-reusable-components-ngtemplateoutlet

    In directive.ts

    
    @Directive({
      selector: '[cardItem]'
    })
    export class CardItemDirective {}
    

    In component.ts

    import { Component, ContentChild, Input, TemplateRef } from '@angular/core';
    import { CardItemDirective } from './card-item.directive';
    import { ListItemDirective } from './list-item.directive';
    
    @Component({
      selector: 'card-or-list-view',
      templateUrl: './card-or-list-view.component.html'
    })
    export class CardOrListViewComponent {
    
      @Input() items: any[] = [];
    
      @Input() mode: 'card' | 'list' = 'card';
    
      // Read in our structural directives as TemplateRefs
      @ContentChild(CardItemDirective, {read: TemplateRef}) cardItemTemplate;
      @ContentChild(ListItemDirective, {read: TemplateRef}) listItemTemplate;
    
    }
    
    

    in component.html

    
      
        
      
    
    

    Happy Coding :)

提交回复
热议问题