访问ng-container中的子组件变量

时间:2019-03-25 16:46:25

标签: angular ng-template ng-content

我有一个名为“建议列表”的自定义组件,该组件从可观察的位置向用户显示建议列表。我已经尽可能通用地创建了此组件,因此您可以传递任何数据数组,因此我希望能够从父项自定义其显示,因为我永远无法确定对象的外观,直到实施它。不幸的是,我无法从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>

2 个答案:

答案 0 :(得分:1)

一种方法是使用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的隐式上下文在模板中传递了建议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:我现在已经编写了这段代码,因此尚未经过测试,但是我认为您可以了解可以做什么!

答案 1 :(得分:0)

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>