【问题标题】:creating a component that accept and iterate over a custom element创建一个接受和迭代自定义元素的组件
【发布时间】:2017-10-03 16:28:51
【问题描述】:

我的目标是创建一个可以采用自定义元素并使用提供的数据对其进行迭代的组件。

这是我能想到的,它工作正常。但我不满意。我想要一些不需要将自定义元素包装在 <template> 标记中的东西。

import {Component, Input, Output, EventEmitter} from 'angular2/core';

@Component({
  selector: 'sub',
  template: `
    <ng-content></ng-content>
  `
})
export class SubComponent  {}

@Component({
  selector: 'my-app',
  template: `
    <sub>
      <template ngFor #listItem [ngForOf]="list" #i="index"> //<--don't want this tag
        <div>{{listItem | json}}</div>
        <p>{{i}}</p>
      </template>
    </sub>
  `,
  directives: [ SubComponent ]
})

export class AppComponent {
  list = [{name: 'John', age: 26},{name: 'Kevin', age: 26},          {name:'Simmons', age:26}];
}
  • 上面的代码是this plunker的编辑。
  • 看到了here的建议,但很模糊。

【问题讨论】:

  • 你有没有看过使用@Input将列表传递给子组件?
  • 可以使用@Input 传递列表数组,但是,这并不能解决将自定义元素包装在template 标记中的问题。
  • 我不确定我是否理解。如果您使用@Input,则您的sub 组件中不需要ng-content
  • 感谢@ChristopherMoore。最终解决了问题。我在下面的回答显示了我想要实现的目标。

标签: javascript angular typescript components transclusion


【解决方案1】:

发现here 可以在ng-content 嵌入上使用指令(早期版本的ng2 没有),所以解决方案很简单:

import {Component, Input, Output, EventEmitter} from 'angular2/core';

@Component({
    selector: 'sub',
    template: `
        <p>content</p>

        <ng-content></ng-content>

        <p>more content</p>

    `
})
export class SubComponent  {}

@Component({
    selector: 'my-app',
    template: `
        <sub >
            <any-element *ngFor="let listItem of list" >
                {{ listItem | json }}
            </any-element>
        </sub>
    `
})

export class AppComponent {
    list = [{name: 'John', age: 26},{name: 'Kevin', age: 26}, {name:'Simmons',     age:26}];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-07
    • 2012-02-25
    • 2022-12-12
    • 1970-01-01
    • 2020-09-27
    • 2014-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多