我正在玩Angular 2,我想要做的就是直接分配給HTML中的一個元素。這可能嗎?你可以在Angular 2中有一個獨立的指令
指令:
import {Directive, ElementRef} from 'angular2/core';
@Directive({
selector: '[Slidernav]'
})
export class Slidernav {
constructor(private element: ElementRef) {
console.log('Slider Run');
}
}
,我將其分配給任何HTML元素像這樣:
<div slidernav>Some content</div>
爲什麼我問的原因是因爲我不想設定的模板與使用組件的DOM中已經存在的HTML相關聯。
編輯
因此,基於響應,這是組件
組件滑塊
import {Component, View, ElementRef} from 'angular2/core';
@Component({
selector: 'Slider',
template: '<ng-content></ng-content>'
})
export class Slider {
constructor(private element: ElementRef) {
console.log('Slider');
}
}
的index.html
<Slider>
<div>hello world</div>
</Slider>
我會期待股利保持在滑塊內內容你好世界。 AFAIK這是它應該如何工作的基礎上我一直在閱讀有關Transclusion。但控制檯錯誤是:
Error: The component Slider has 1 <ng-content> elements, but only 0 slots were provided.
我真的不明白你想實現什麼的HTML模板的組成部分。聽起來像一個模板的組件,只用' '做你想做的。 –
我沒有看到任何錯誤。對我來說,這看起來像一個錯誤。只是出於好奇。你能否請'hello world '(沒有空格或換行符)? –
我已經更新了它,它仍然拋出一個錯誤。 –