简体   繁体   English

如何在Angular2中创建容器组件

[英]How to make a container component in Angular2

I'm learning angular2, What I'm basically trying to do is to create a component, that (some how), could contain other components. 我正在学习angular2,我基本上要做的是创建一个组件,(某些方法),可以包含其他组件。

I mean, I want a to create a component Card that could have content inside. 我的意思是,我想创建一个可以包含内容的组件Card

This is an example: 这是一个例子:

<Card>
   <span>Some Content</span>
</Card>

I want to could re-use Card many times, how can I create a component like that? 我想多次重复使用Card,我怎样才能创建这样的组件?

您可以在组件的模板中使用指令<ng-content></ng-content>在该位置插入内容。

If you're using TypeScript (which angular recommends), you can import a component with a selector defined, add it as directive and use the selector in the HTML of the encompassing component. 如果您正在使用TypeScript(建议使用角度),则可以导入已定义选择器的组件,将其添加为指令并在包含组件的HTML中使用选择器。 This can be done as follows: 这可以按如下方式完成:

cards.ts

import { Component } from '@angular/core';

@Component({
  selector: 'card',
  template: '<span>Some Content</span>'
})
export class CardComponent {

}

container.ts

import { Component }     from '@angular/core';
import { CardComponent } from './cards.ts';

@Component({
  directives: [CardComponent],
  template: '<div><card></card><card></card></div>'
})
export class ContainerComponent {
}

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

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