Angular2:用组件的模板替换宿主元素 [英] Angular2: replace host element with component's template

查看:20
本文介绍了Angular2:用组件的模板替换宿主元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular 的新手,特别是 angular2.我正在尝试编写一个容器组件,其中应该包含子组件.

I'm new to angular in general and to angular2 specifically. I'm trying to write a container component, which should have child components in it.

例如容器组件:

@Component({
  selector: 'my-list',
  template: `
    <ul>
      <ng-content></ng-content>
    </ul>
  `
})
export class MyList {
}

子组件:

import { Component } from 'angular2/core'

@Component({
  selector: 'my-item',
  template: `
    <li>
      <ng-content></ng-content>
    </li>
  `
})
export class MyItem {
}

我想做这个结构:

<my-list>
    <my-item>One</my-item>
    <my-item>Two</my-item>
</my-list>

要渲染到以下内容:

<my-list>
    <ul>
        <li>One</li>
        <li>Two</li>
    </ul>
</my-list>

但相反,我保留了容器的宿主元素和项目:

But instead, I have the host element of the container and the items preserved as well:

<my-list>
    <ul>
        <my-item>
            <li>One</li>
        </my-item>
        <my-item>
            <li>Two</li>
        </my-item>
    </ul>
 </my-list>

Plunk 在此处可用

问题:有没有办法消除宿主元素而只留下渲染的模板?

Question: is there a way to eliminate the host elements and to leave only the rendered template?

推荐答案

最后我找到了解决方案:将 ElementRef 注入到 MyItem 并使用其 nativeElement.innerHTML:

Finally I found solution: injecting ElementRef to MyItem and using its nativeElement.innerHTML:

我的列表:

import { Component, ContentChildren, QueryList } from 'angular2/core'
import { MyItem } from './myitem'

@Component({
  selector: 'my-list',
  template: `
    <ul>
      <li *ngFor="#item of items" [innerHTML]="item.innerHTML"></li>
    </ul>
  `
})
export class MyList {
  @ContentChildren(MyItem) items: QueryList<MyItem>
}

我的物品:

import { Directive, Inject, ElementRef } from 'angular2/core'

@Directive({selector: 'my-item'})
export class MyItem {
  constructor(@Inject(ElementRef) element: ElementRef) {
    this.innerHTML = element.nativeElement.innerHTML
  }
}

工作狂在这里

这篇关于Angular2:用组件的模板替换宿主元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆