Angular2 子组件作为数据 [英] Angular2 child component as data

查看:30
本文介绍了Angular2 子组件作为数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个组件:parentchild.HTML 将如下所示:

Let's say I have two components: parent and child. The HTML would look like this:

<parent title="Welcome">
    <child name="Chris">Blue Team</child>
    <child name="Tom">Red Team</child>
</parent>

最终输出如下:

<h1>Welcome</h2>
<ul>
    <li><b>Chris</b> is on the Blue Team</li>
    <li><b>Tom</b> is on the Red Team</li>
</ul>

父组件:

@Component({
  selector: 'parent',
  directives: [ChildComponent], // needed?
  template: `
    <h1>{{title}}</h1>
    <ul>
       <li *ngFor="#child of children()">{{child.content}}<li>
    </ul>`
})
export class ParentComponent {

    @Input() title;

    children() {
        // how?
    }

}

如何从父组件访问子组件并获取它们的内容?

How do I access the child components from within the parent and get their content?

另外,我不希望孩子被自动渲染.根据某些情况,我可能会选择不给某些孩子看.

Also, I don't want the children to be automatically rendered. Depending on some conditions I may choose not to show certain children.

谢谢.

推荐答案

要将内容投影到元素(嵌入),您需要 <ng-content> 元素,如

For projecting content to an element (transclusion) you would need the <ng-content> element like

@Component({
  selector: 'parent',
  directives: [ChildComponent], // needed?
  template: `
    <h1>{{title}}</h1>
    <ul>
       <li *ngFor="letchild of children()">
         <ng-content></ng-content>
       </li>
    </ul>`
})

但这不适用于您的用例,因为 <ng-content> 不生成内容,它只投影它(用作占位符,其中子项显示在您的组件模板中.

but that won't work for your use case because <ng-content> doesn't produce content, it only projects it (works as a placehoder where children are displayed within your components template.

即使 *ngFor 会产生 3 个 元素,子元素也只会在第一个 中显示一次; 元素.

Even though *ngFor would produce 3 <ng-content> elements, the children would only be displayed once in the first <ng-content> element.

允许使用像

<ng-content select="[name=Chris]"></ng-content>

模板如

<ul>
   <li>
     <ng-content select="[name=Chris]"></ng-content>
   </li>
</ul>`

会导致

<h1>Welcome</h2>
<ul>
    <li><b>Chris</b> is on the Blue Team</li>
</ul>

绑定中解释的更灵活和强大的方法在 Angular 2 中使用 ngForTemplate 时的事件(来自 @kemsky 的评论)

A more flexible and powerful approach explained in Binding events when using a ngForTemplate in Angular 2 (from @kemsky s comment)