2016-02-27 56 views
1

版本: 「angular2」: 「2.0.0-beta.6」Angular2:組件倍數指令組成

我們假定我們有兩個@Directive

  • HighLightDirective
  • UnderlineDirective

如何創建一個實現這兩個@Directive@Component? PS:我知道我可以通過更改組件模板來做到這一點,如下所示。有更優雅的東西存在嗎?

'<div highlight underline>{{text}}</div>' 
+2

這正是該指令是,你應該如何使用它們(:比如你給'{{文本}}'是有點微不足道,其他一切屬性指令是很好的解決方案你是否有更具體的東西。介意 – Sasxa

+0

@Sasxa我很困惑在我做的每個組件添加一個div容器,它創建'

my_text
''時 my_text'看起來要容易得多:] – plone1

+0

使用'<測試亮點下劃線>在'父模板。 – Sasxa

回答

1
//Looking from something like that.. 
//using: [HighLightDirective, UnderlineDirective] 

什麼你要找的是directives屬性:

@Component({ 
    selector: 'test', 
    template: '<div highlight underline>{{text}}</div>', 
    directives: [HighLightDirective, UnderlineDirective] // don't forget to import them! 
}) 
export class TestComponent { 
    @Input() // don't forget this! 
    public text:string; 
    constructor() {} //no need to do anything here 
} 

最初我誤解你的問題,以爲你只是感到困惑元數據鍵使用 - 如果你是,然後看上面。根據「自動」將這些指令應用到組件模板,恕我直言,沒有什麼不適宜將它們應用到模板中,因爲您有任何「更優雅」的東西會比例不太清晰。無論如何,不​​,沒有其他選擇,做你在這裏做的事情是非常地道的。

這是所有假設你的實際使用情況比這個問題更復雜,否則(因爲你不能在你的模板中添加任何新的東西)Component是這裏的錯誤的工具,你應該簡單地直接申請兩項指令。如果你真的,堅決反對這樣做,和你的使用情況實際上是這個簡單,我想

@Component({ 
    selector: 'test', 
    template: '<div highlight underline><ng-content></ng-content></div>', 
    directives: [HighLightDirective, UnderlineDirective] 
}) 
export class TestComponent { } 

然後你可以使用如下:<test>stuff</test>而非<test [text]="someVar"></test>會更優雅......但它對我來說仍然沒有多大意義。

2

您可以對指令和組件使用相同的選擇器。

@Directive({selector: 'test'}) 
class HighlightDirective { 
} 

@Directive({selector: 'test'}) 
class UnderlineDirective {} 

@Component({ 
    selector: 'test', 
    directives: [] 
    template: '{{text}}', 
    //Looking from something like that.. 
    //using: [HighLightDirective, UnderlineDirective] 
}) 
export class TestComponent { 
    constructor(@Self()hs:HighlightDirective, @Self()hs:UnderlineDirective) {} 
} 

@Component({ 
    selector: 'my-app', 
    directives: [TestComponent,HighlightDirective, UnderlineDirective] 
    template: ` 
    <h2>Hello</h2> 
    <test></test> 

` 
}) 
export class App { 

} 

Plunker example

如果你想使用的指令independendly組件,你可以添加多個選擇像

@Directive({selector: 'test,highlight'}) 
class HighlightDirective { 
} 

的構造函數拋出時HighlightDirectiveUnderlineDirective不應用

constructor(@Self()hs:HighlightDirective, @Self()hs:UnderlineDirective) {} 

您也可以將指令添加到PLATFORM_DIRECTIVES

bootstrap(MyComponent, [provide(PLATFORM_DIRECTIVES, {useValue: [HighlightDirective, UnderlineDirective], multi:true})]); 

,讓他們處處應用其中,選擇匹配,沒有將其添加到每一個部件的directives: [HighlightDirective, UnderlineDirective]要使用它們。