版本: “angular2”: “2.0.0-beta.6”Angular2:组件倍数指令组成
我们假定我们有两个@Directive
HighLightDirective
UnderlineDirective
如何创建一个实现这两个@Directive
的@Component
? PS:我知道我可以通过更改组件模板来做到这一点,如下所示。有更优雅的东西存在吗?
'<div highlight underline>{{text}}</div>'
版本: “angular2”: “2.0.0-beta.6”Angular2:组件倍数指令组成
我们假定我们有两个@Directive
HighLightDirective
UnderlineDirective
如何创建一个实现这两个@Directive
的@Component
? PS:我知道我可以通过更改组件模板来做到这一点,如下所示。有更优雅的东西存在吗?
'<div highlight underline>{{text}}</div>'
//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>
会更优雅......但它对我来说仍然没有多大意义。
您可以对指令和组件使用相同的选择器。
@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 {
}
如果你想使用的指令independendly组件,你可以添加多个选择像
@Directive({selector: 'test,highlight'})
class HighlightDirective {
}
的构造函数抛出时HighlightDirective
和UnderlineDirective
不应用
constructor(@Self()hs:HighlightDirective, @Self()hs:UnderlineDirective) {}
您也可以将指令添加到PLATFORM_DIRECTIVES
bootstrap(MyComponent, [provide(PLATFORM_DIRECTIVES, {useValue: [HighlightDirective, UnderlineDirective], multi:true})]);
,让他们处处应用其中,选择匹配,没有将其添加到每一个部件的directives: [HighlightDirective, UnderlineDirective]
要使用它们。
这正是该指令是,你应该如何使用它们(:比如你给'{{文本}}'是有点微不足道,其他一切属性指令是很好的解决方案你是否有更具体的东西。介意 – Sasxa
@Sasxa我很困惑在我做的每个组件添加一个div容器,它创建'my_text ''时 my_text '看起来要容易得多:] –
plone1
使用'<测试亮点下划线>在'父模板。 – Sasxa