那么问题来了, 如何用 angular 来实现这样的一个组件?
卡片的页眉和页脚只能显示文本;
卡片的主体能够显示任意内容, 也可以是其它组件;
这就是所谓的包含。
创建包含组件
在 angular 中, 所谓的包含就是在定义固定视图模板的同时, 通过
标签来定义一个可以放动态内容的位置。 下面就来实现一个简单的卡片组件。
卡片组件的类定义为:
// card.component.ts import { Component, Input, Output } from '@angular/core'; @Component({ selector: 'app-card', templateUrl: 'card.component.html', }) export class CardComponent { @Input() header: string = 'this is header'; @Input() footer: string = 'this is footer'; }
@Input 是一个声明, 允许从父组件传入任意的文本。
卡片组件的的视图模板定义为:
为了能够在其它组件中使用, 需要在对应的 AppModule 中添加声明:
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { CardComponent } from './card.component'; // import card component @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent, CardComponent ], // add in declaration bootstrap: [ AppComponent ], }) export class AppModule { }
如果使用了 angular-cli 来生成这个组件的话, 会自动在 AppModule 中添加声明。
使用卡片组件
在另外一个组件 AppComponent 中使用刚刚创建的卡片组件的话, 代码如下所示:
Single slot transclusion