Angular2:如何在组件内部显示组件标签的内部HTML?
发布时间:2020-12-17 17:51:23 所属栏目:安全 来源:网络整理
导读:我对angular2有疑问.我正在创建一些组件,并希望有这样的东西: 这是我的DogComponent类: @Component({ selector: "dog",template: "dog.template.html"})class DogComponent{ @Input() image: string;} 以及dog.template.html中的模板: div !-- Content of
我对angular2有疑问.我正在创建一些组件,并希望有这样的东西:
这是我的DogComponent类: @Component({ selector: "dog",template: "dog.template.html" }) class DogComponent { @Input() image: string; } 以及dog.template.html中的模板: <div> <!-- Content of <top> should go here --> <img class="after" src="dogs/{{image}}" /> <!-- Content of <bottom> should go here --> </div> 当我使用DogComponent时,它应该使用传递的src创建img-tag,还要查看图像之前和之后的其他HTML部分. 所以最后,如果我写这段代码: <dog image="garry.png"> <top> <h1>This is Garry!</h1> </top> <bottom> <span>He is my favorite dog!</span> </bottom> </dog> 它应该呈现给: <dog> <div> <h1>This is Garry!</h1> <img src="dog.png" /> <span>He is my favorite dog!</span> </div> </dog> 有人有我的问题的答案吗? 这会很棒! 编辑: 感谢您的建议,所以现在我更新了我的片段并添加了DogListComponent.如果我在我的应用程序中的某处使用标记dog-list,则应该查看最后一个片段(浏览器结果).希望它现在有点清晰了. dog.component.ts @Component({ selector: "dog",templateUrl: "dog.template.html" }) class DogComponent { @Input() image: string; } dog.template.html <div> <!-- Content of <top> should go here --> <img class="after" src="dogs/{{image}}" /> <!-- Content of <bottom> should go here --> </div> dog_list.component.ts @Component({ selector: "dog-list",templateUrl: "dog-list.template.html" }) class DogListComponent { } 狗list.template.html <dog image="garry.png"> <top> <h1>This is Garry!</h1> </top> <bottom> <span>He is my favorite dog!</span> </bottom> </dog> <dog image="linda.png"> <top> <h1>My little Linda :)</h1> </top> <bottom> <span>She is my cutest dog!</span> </bottom> </dog> <dog image="rex.png"> <top> <h1>And here is Rex!</h1> </top> <bottom> <span>DANGEROUS!</span> </bottom> </dog> 浏览器结果: <dog-list> <dog image="garry.png"> <top> <h1>This is Garry!</h1> </top> <bottom> <span>He is my favorite dog!</span> </bottom> </dog> <dog image="linda.png"> <top> <h1>My little Linda :)</h1> </top> <bottom> <span>She is my cutest dog!</span> </bottom> </dog> <dog image="rex.png"> <top> <h1>And here is Rex!</h1> </top> <bottom> <span>DANGEROUS!</span> </bottom> </dog> <dog-list> 解决方法
所以我找到了解决方案!我需要使用< ng-content>.
dog.template.html看起来像这样: <div> <ng-content select="top"></ng-content> <img class="after" src="dogs/{{image}}" /> <ng-content select="bottom"></ng-content> </div> 然后它将在我的div中插入指定的< top> -tags和< bottom> -tags. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |