我有一个名为 Suggestion List 的自定义组件,它向用户显示来自可观察对象的建议列表。我已经尽可能通用地创建了这个组件,这样你就可以传递任何数据数组,所以我希望能够从父级自定义它的显示,因为我永远不知道对象会是什么样子,直到实现它。不幸的是,我无法从 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>
最佳答案
一种方法是使用 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
的隐式上下文在模板中传递建议变量:
<ng-container *ngFor="let suggestion of suggestions>
<ng-container *ngTemplateOutlet="suggestionTemplate; context: {$implicit: suggestion}"></ng-container>
</ng-container>
在子组件的.ts文件中,声明传入的模板如下:
@Input() suggestionTemplate: TemplateRef<any>;
PS:这段代码是我现在写的,所以还没有测试,但我想你可以知道你能做什么!
关于angular - 在 ng-container 中访问子组件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55342690/