当将ngFor用作投影内容时,如何从其上下文中拔出ngFor并将其插入包装它的组件的上下文中?

时间:2019-07-19 14:34:52

标签: angular

我创建了一个将SET @carerfname = 'Liane'; SET @carersname = 'Cartman'; SELECT CONCAT(C.child_sname, ' ', C.child_fname) AS 'child_name', A.activity_name, A.activity_day FROM Child C JOIN Childactivity CA ON (CA.child_id = C.child_id) JOIN Activity A ON (A.activity_id = CA.activity_id) WHERE @carersname AND @carerfname SET @carerfname = 'Liane'; SET @carersname = 'Cartman'; SELECT CONCAT(C.child_sname, ' ', C.child_fname) AS 'child_name', A.activity_name, A.activity_day FROM Child C JOIN Childactivity CA ON (CA.child_id = C.child_id) JOIN Activity A ON (A.activity_id = CA.activity_id) WHERE @carersname AND @carerfname LIMIT 0, 1000 0 row(s) returned 0.000 sec / 0.000 sec 作为投影内容的包装组件。

我想用包装组件的内容替换投影内容的立即绑定。

我知道,使用<div *ngFor='let item of items>可以定义一个关联的上下文对象。但是我不知道这怎么用。

注意:预计的内容不必是*ngTemplateOutlet,但必须是支持div的元素。

*ngFor
    Component({
      selector: 'some-component',
      template: `
          <wrapper>
            <div *ngFor="let item of items" <-- make items refer to items in wrapper and not some-component">
<span>{{item}}</span>
</div>
           <wrapper>
      `
    })
    class SomeComponent{
      items = ['text 1'] <-- replace this ngFor binding
    }

我希望范围显示为“文本2”而不是“文本1”。

@MartinSchneider-修改示例


    Component({
      selector: 'wrapper',
      template: `
          <ng-content></ng-content>
      `
    })
    class Wrapper {
      items = ['text 2'] <-- bind ngFor items to this member
    }
@Component({
  selector: 'my-wrapper',
  template: `
    <ng-container *ngFor="let item of items">
      <ng-content *ngTemplateOutlet="myItemTmpl, context: { $implicit: items}"></ng-content>
    </ng-container>
  `
})
export class MyWrapperComponent {
  @ContentChild('myItem', {static: false}) myItemTmpl: TemplateRef<any>; 

  items = [
    { id: 0, name: "foo"},
    { id: 1, name: "bar"}
  ];

}

1 个答案:

答案 0 :(得分:1)

是否与该问题类似:
How to render multiple ng-content inside an ngFor loop using Angular 4?

所以,像这样:

import { Component, ContentChild, TemplateRef } from '@angular/core';

@Component({
  selector: 'my-wrapper',
  template: `
    <ng-container *ngFor="let item of items">
      <ng-container *ngTemplateOutlet="myItemTmpl, context: { $implicit: item }"></ng-container>
    </ng-container>
  `
})
export class MyWrapperComponent {
  @ContentChild('myItem', {static: false}) myItemTmpl: TemplateRef<any>; 

  items = [
    { id: 0, name: "foo"},
    { id: 1, name: "bar"}
  ];

}
<my-wrapper>
  <ng-template #myItem let-item>
    <h3>{{item.name}}</h3>
    <p>ID: {{item.id}}</p>
  </ng-template>
</my-wrapper>