[Angular 2] Transclusion in Angular 2

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Angular 2] Transclusion in Angular 2相关的知识,希望对你有一定的参考价值。

Link: Blog

 

Single transclude:

<ng-content></ng-content>

 

Multi-translcude:

<ng-content select=".label"></ng-content>
<ng-content select=".title"></ng-content>

 

 

import {Component} from 'angular2/core';
import {bootstrap} from 'angular2/bootstrap';
import {TodoService} from './TodoService';
import {TodoInput} from './TodoInput';
import {TodoList} from './TodoList';
import {StatusSelector} from './StatusSelector';
@Component({
selector: 'app',
directives: [TodoInput, TodoList, StatusSelector],
template: `
<todo-input>
Hi, Dudu, this is transclude content
</todo-input>
<status-selector (selectedStatus)="status=$event"></status-selector>
<todo-list [status]="status">
<div class="label">Label</div>
<div class="title">Title</div>
</todo-list>
`
})
class App {
}
// []: we can inject service which can be used for the whole app
bootstrap(App, [
TodoService
]);
view raw main.ts hosted with ❤ by GitHub
import {Component} from 'angular2/core';
import {TodoService} from './TodoService';
import {TodoModule} from './TodoModule';
@Component({
selector: 'todo-input',
template: `
<form (submit)="onSubmit()">
<ng-content></ng-content>
<input type="text" [(ngModel)]="todoModule.title">
</form>
`
})
export class TodoInput {
// Init a todoModule
todoModule:TodoModule = new TodoModule();
constructor(public todoService:TodoService) {
}
onSubmit() {
this.todoService.addNewTodo(this.todoModule);
// After insert, create new TodoModule
this.todoModule = new TodoModule();
console.log(this.todoService.todos);
}
}
view raw TodoInput.ts hosted with ❤ by GitHub
import {Component, Input} from 'angular2/core';
import {TodoService} from './TodoService';
import {TodoItemRenderer} from './TodoItemRenderer';
import {StartedPipe} from './started-pipe';
@Component({
selector: 'todo-list',
pipes: [StartedPipe],
directives: [TodoItemRenderer],
template: `
<div>
<ng-content select=".label"></ng-content>
<ng-content select=".title"></ng-content>
<ul>
<li *ngFor="#todo of todoService.todos | started : status">
<todo-item-renderer [todo]="todo"
(toggleTodo) = "todoService.toggleTodo($event)"
></todo-item-renderer>
</li>
</ul>
</div>
`
})
export class TodoList{
@Input() status;
constructor(public todoService: TodoService){
}
}
view raw TodoList.ts hosted with ❤ by GitHub

以上是关于[Angular 2] Transclusion in Angular 2的主要内容,如果未能解决你的问题,请参考以下文章

Angular:嵌入,设置SVG元素的颜色

AngularJS中的transclusion案例

Vue学习笔记入门篇——组件的内容分发(slot)

Vue内容分发slot

Vue内容分发slot

Angular 2 - 如何使用新的 Angular 2.0.0-rc.1 路由器