javascriptangularangularjs-ng-transcludetransclusion

How to Add ElementRef into local dom?


I want to crate a layout component to arrange groups of items, like:

<garden-bed>
  <div #veg (click)="pluck()">carrot</div>
  <div #veg (click)="pluck()">cabbage</div>
  <div #veg (click)="pluck()">turnip</div>
</garden-bed>

The component so far looks like

@Component({
  selector: 'app-garden-bed',
  templateUrl: './garden-bed.component.html',
})
export class GardenBed  {

  @ContentChildren('veg') vegs: QueryList<ElementRef>;

  constructor() { }


  ngAfterViewInit() {
    console.log('this.vegs=' + JSON.stringify(this.vegs));
  }

}

but I can't figure out how to plant them in the tamplate (garden-bed.component.html):

  <div *ngFor="let veg of vegs">
     <ng-content/ng-template  *something="veg"></ng-template>
     but this doesn't work.
     veg should appear here and all its binding should work!

  </div>

any help is highly appreciated!


Solution

  • To avoid issues with change detection you should get the templateRefs out of the QueryList using toArray only once:

      templates: TemplateRef[];
    
      ngAfterViewInit() {
        console.log('this.vegs=' + JSON.stringify(this.vegs));
        this.templates = this.vegs.toArray();
      }
    

    then use ngTemplateOutlet to stamp the templat

      <div *ngFor="let veg of templates">
         <ng-container *ngTemplateOutlet="veg"></ng-container>
         but this doesn't work.
         veg should appear here and all its binding should work!
    
      </div>
    

    ngTemplateOutlet also allows to pass context data that can be bound to in the template

    See also

    Don't get confused by <ng-template [ngTemplateOutlet]="myTemplate", it's just alternate syntax to what I showed above