我有一个名为Suggestion的自定义组件,它向用户显示来自可观察对象的建议列表。我已经创建了尽可能通用的这个组件,这样你就可以传递任何数据数组,所以我希望能够从父级定制它的显示,因为在实现它之前,我永远不能确定对象看起来是什么样子。不幸的是,我不能访问ng-container中父组件的子组件变量。
使用ng-container或ng-template可以做到这一点吗?或者我应该完全采用另一种方法?
父组件
<suggestion-list (suggestionSelected)="selectSuggestion($event)" [$suggestions]="$suggestionSource">
<ng-container>
{{suggestion.firstname + ' ' + suggestion.lastname}}
<ng-container>
</suggestion-list>子组件
<mat-list role="list">
<mat-list-item *ngFor="let suggestion of $suggestions | async">
<mat-icon mat-list-icon>person</mat-icon>
<mat-card (click)="selectSuggestion(suggestion)">
<ng-container></ng-container>
</mat-card>
</mat-list-item>
</mat-list>发布于 2019-03-26 01:03:58
一种方法是使用ng-template。可以为父组件中的每个元素定义一个模板,并在子组件中为数组中的每个元素显示该模板:
父组件:
<suggestion-list (suggestionSelected)="selectSuggestion($event)"
[suggestions]="$suggestionSource | async"
[suggestionTemplate]="suggestionTemplate">
</suggestion-list>
<ng-template #suggestionTemplate let-suggestion>
<span>{{suggestion.firstname + ' ' + suggestion.lastname}}</span>
</ng-template>在您的子组件中,您可以这样做(请注意,我们通过ng-template的隐式上下文传递了模板中的suggestion var
<ng-container *ngFor="let suggestion of suggestions>
<ng-container *ngTemplateOutlet="suggestionTemplate; context: {$implicit: suggestion}"></ng-container>
</ng-container>在子组件的.ts文件中,您可以像这样声明传入的模板:
@Input() suggestionTemplate: TemplateRef<any>;PS:我现在已经写了这段代码,所以它没有经过测试,但我想你可以知道你能做什么!
发布于 2019-03-26 00:51:40
Here就是一个工作示例
parent.component.html
<div>
<suggestion-list (suggestionSelected)="selectSuggestion($event)" [$suggestions]="$suggestionSource">
<p>{{suggestion.firstname + ' ' + suggestion.lastname}}</p>
</suggestion-list>
</div>child.component.html
<div>
<ng-content></ng-content>
<p>Hello !</p>
</div>https://stackoverflow.com/questions/55342690
复制相似问题