Creating a dynamic repeater with ng-content transclusion

前端 未结 1 425
独厮守ぢ
独厮守ぢ 2020-12-03 08:45

What I\'m trying to achieve is a generic component that is bound to an array of arbitrary objects that allows adding and removing rows dynamically when the view of each row

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-03 09:33

    You could use ngTemplateOutlet to achieve it.

    Following are the steps in implementing dynamic repeater:

    First step is to provide a TemplateRef as a child element of the RepeaterComponent:

    
      
        ...
      
    
    

    Second step is to query this template within RepeaterComponent via @ContentChild:

    export class RepeaterComponent { 
      @ContentChild(TemplateRef) itemTemplate: TemplateRef;
      ...
    

    Third step is use ngTemplateOutlet to render the template:

    @Component({
      selector: 'repeater',
      template: `
        
        
    ` }) export class RepeaterComponent { @Input() repeaterArray: Array; @ContentChild(TemplateRef) itemTemplate: TemplateRef; ... }

    Fourth step is to use reference to the row inside TemplateRef within MasterComponent (just back to our first step):

    
      
    
    

    Notice: we are passing ngOutletContext like object with $implicit property.

    using the key $implicit in the context object will set it's value as default.

    It works as follows:

    [ngTemplateOutletContext]="{ $implicit: row }"  ==>