我有一个名为“select-other”的组件,里面有两个元素,我需要获取其内容并在“select-other”组件模板中打印。
HTML
<select-other>
<options>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</options>
<other>
<input>
<button></button>
</other>
</select-other>
组件装饰器
@Component({
selector: 'select-other',
template: `
<select
*ngIf="select !== 'other'"
[(ngModel)]="select"
class="form-control"
>
// CONTENT FROM INSIDE <OPTIONS> HERE
<option
value="other"
>Other</option>
</select>
// CONTENT FROM INSIDE <OTHER> HERE
`
})
我知道我可以在模板中使用“ng-content”来打印“select-other”标签之间的内容,但我有点困惑如何从不同元素中获取内容并进行打印它们位于模板中我想要的位置。
提前致谢。
最佳答案
您可以像这样使用ng-content
内容投影:
@Component({
selector: 'select-other',
template: `
<select
*ngIf="select !== 'other'"
[(ngModel)]="select"
class="form-control">
// CONTENT FROM INSIDE <OPTIONS> HERE
<ng-content select="options"></ng-content>
<option value="other">Other</option>
</select>
// CONTENT FROM INSIDE <OTHER> HERE
<ng-content select="other"></ng-content>
`
})
因此您可以通过其父元素选择器来选择所需的内容。 有关此的更多信息 here
关于angular - 组件模板内的嵌套内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40249646/