如何将ElementRef添加到本地dom?

时间:2018-02-16 14:21:45

标签: javascript angular angularjs-ng-transclude transclusion

我想创建一个布局组件来安排项目组,例如:

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

到目前为止,该组件看起来像

@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));
  }

}

但我无法弄清楚如何在模板中植入它们(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>

任何帮助都非常感谢!

1 个答案:

答案 0 :(得分:0)

为了避免更改检测问题,您应该仅使用QueryListtoArray获取templateRef:

  templates: TemplateRef[];

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

然后使用ngTemplateOutlet标记模板

  <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还允许传递可以绑定到模板中的上下文数据

另见

不要被<ng-template [ngTemplateOutlet]="myTemplate"弄糊涂,它只是我上面展示的替代语法