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

查看:176
本文介绍了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 {
}

我想做一个这样的结构:

I'd like to make this structure:

<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>

但是,相反,我具有容器的host元素以及保留的项目:

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>

可在此处使用插件

问题:是否可以消除宿主元素并仅保留渲染的模板?

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天全站免登陆