gpt4 book ai didi

html - Angular 2 : How to show inner HTML of component-tags inside of component?

转载 作者:太空狗 更新时间:2023-10-29 15:36:57 26 4
gpt4 key购买 nike

我有一个关于 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 ,则应该查看最后一个片段(浏览器结果)。希望现在更清楚了。

狗.component.ts

@Component({
selector: "dog",
templateUrl: "dog.template.html"
})
class DogComponent
{
@Input() image: string;
}

狗.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
{
}

狗列表.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>

然后它将插入指定的<top>-tags<bottom>-tags在我的分区中。

关于html - Angular 2 : How to show inner HTML of component-tags inside of component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com