简体   繁体   中英

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.

I mean, I want a to create a component Card that could have content inside.

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?

您可以在组件的模板中使用指令<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. 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 {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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