2016-10-16 127 views
2

我目前正在尝试看看,如果在Angular 2中我们可以创建动态选择器/ html标签。例如,我想要做这样的事情:Angular 2:动态选择器属性

@Component({ 
    selector: 'my-app' + 'variableName', 
    template: ` 
    <container> </container> 
    `, 
    directives: [ContainerComponet] 
}) 

,这样我可以这样做:

<my-app + {{variableName}}> <!-- the variable name would be coming from a public variable inside my component--> 

在某种程度上,我的组件的实现需要发生好几次,我知道我可以复制/粘贴我拥有的多个组件,但是我觉得必须有更智能的方法。

+0

有一些技巧通过在运行时动态创建组件来实现类似帽子的东西。另一种可能适用于你的方法是http://stackoverflow.com/questions/36325212/angular-2-dynamic-tabs-with-user-click-chosen-components/36325468#36325468 –

+1

就像'完全不受支持。 Angular从不匹配动态创建内容的选择器。最近有讨论支持诸如'[someSelector] =“boolValue?true:null”'等选择器的指令。 –

+0

感谢Gunter!我会考虑链接 – eagleEye

回答

0

这对我有效,在我的情况下模板是相同的,但它需要根据某些值更改(着色更改)。因此,在父组件这些值设定,并根据我的分量表现不同

码组元:

sample.ts

@Component({ 
    selector: 'my-app-sample' 
    templateUrl: 'sample.html' 
}) 

@Input() myInput: MyInput; 

该组件和模板(sample.ts),是一另一个组件的孩子。 在父模板中,我们“滴”德样本选择:我的应用程序内样本

模板,我将我的选择(父):

<div> 
<my-app-sample [myInput] = "anotherVariable"</my-app-sample> 
</div> 

注:anotherVariable值设置在组件父。