简体   繁体   English

如何在ng-template中呈现ContentChildren元素?

[英]How do you render ContentChildren elements in an ng-template?

Given a component, I wish to wrap the rendered child elements in it. 给定一个组件,我希望将渲染的子元素包装在其中。

How is this possible in angular2? 在angular2中这怎么可能?

For example, I have this component: 例如,我有此组件:

export class InnerTestComponent implements OnInit {
  @ContentChildren('link') contents: QueryList<ElementRef>;
}

and this template: 和这个模板:

<div>
  <h3>Children test: {{ contents.length }} to render</h3>
  <div *ngFor="let child of contents">
    <ng-container *ngTemplateOutlet="someTemplateName; context: {child: child}">
    </ng-container>
  </div>
</div>

<ng-template #someTemplateName let-child="child">
  <h3>Child</h3>
  <div>
    {{ child }}
  </div>
</ng-template>

And when I call: 当我打电话时:

<templates-inner-test>
  <a #link href="#">Test1</a>
  <a #link href="#">Test2</a>
</templates-inner-test>

I get: 我得到:

<templates-inner-test>
<div>
  <h3>Children test: 2 to render</h3>
  <h3>Child</h3>
  <div>
    [object Object] <--- WRONG
  </div>
  </div><div>
  <h3>Child</h3>
  <div>
    [object Object] <--- WRONG
  </div>
  </div>
</div>
</templates-inner-test>

When what I want is: 当我想要的是:

<h3>Child</h3>
<div>
  <a href="#">Test1</a>
</div>
<h3>Child</h3>
<div>
  <a href="#">Test2</a>
</div>

I appreciate rendering an ElementRef in {{ ... }} simply executes toString() on it, but what should I be doing instead? 我很欣赏在{{ ... }}渲染ElementRef只需在其上执行toString() ,但是我应该怎么做呢?

I would like to also specifically point out that the solutions floating around in various places to use the <ng-content select="child"></ng-content> flat out don't work. 我还要特别指出,在各处浮动以使用<ng-content select="child"></ng-content>解决方案不起作用。 That just renders an empty <div> . 那只是渲染一个空的<div>

Since contents is a list ElementRef , and you are looping through it, child is a ElementRef, so you probably need to use child.nativeElement.innerHTML . 由于contents是一个ElementRef列表,并且您正在遍历整个列表,因此child是ElementRef,因此您可能需要使用child.nativeElement.innerHTML

But you definitely need to use DomSanitizer here, with it you could probably do the following 但是您肯定需要在此处使用DomSanitizer ,通过它您可以执行以下操作

import { Pipe, PipeTransform } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({name: 'safeHtml'})
export class SafeHtml implements PipeTransform  {
    constructor(private sanitizer:DomSanitizer){}
    transform(style) {
        return this.sanitizer.bypassSecurityTrustHtml(style);   
    }
}

Then you could 那你可以

<ng-template #someTemplateName let-child="child">
    <h3>Child</h3>
    <div [innerHTML]="child.nativeElement.innerHTML | safeHtml" ></div>
</ng-template>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM