ng内的Angular 6 ngTemplateOutlet用于多个上下文

Bae*_*ree 4 ngfor angular angular6

假设我具有以下组件:

@Component({
  selector: 'todo-lib',
  template: `
<li *ngFor="let todo of libService.todos">
  <div class="view">
    <label>{{todo.title}}</label>
    <ng-container *ngTemplateOutlet="incomingTemplate;context:ctx"></ng-container>
  </div>
</li>

<ng-template #incomingTemplate let-service="templateService">
<button (click)="service.removeTodo(todo)">delete</button>
</ng-template>
`,
  styles: []
})
export class TodoLibComponent implements OnInit {

  ctx = {
    templateService: this.libService
  };
Run Code Online (Sandbox Code Playgroud)

待办事项列表在libService内部。我不会在这里发布它,因为它的逻辑无关紧要。“ ng-template”将从另一个组件中注入,并将删除按钮添加到我的待办事项列表中。这意味着:通常没有删除选项,除了将提供“ ng-template”

但是,此方法将失败,并出现以下错误:

message: "_v.context.todo is undefined"
Run Code Online (Sandbox Code Playgroud)

由于“ todo”不是上下文对象“ ctx”的一部分,因此无法访问它。为了实现这一点,我将被迫这样做:

<ng-container *ngTemplateOutlet="incomingTemplate;context:{ todo: todo}">
Run Code Online (Sandbox Code Playgroud)

这将允许我访问待办事项对象,但不再访问服务。

看来我无法同时访问ngFor AND和在ctx属性中定义的服务定义的todo属性。是否有解决方案来实现两者?

干杯

Bae*_*ree 5

我还在Angular的官方github存储库中提到了这一点。开发人员的corrext分析器是:

@dawidgarus:您可以这样做:

<ng-container *ngTemplateOutlet="incomingTemplate;context:{ todo: todo, templateService: libService }">
Run Code Online (Sandbox Code Playgroud)

此外:

@dawidgarus的建议是一个很好的建议,并遵循作用域在当前Angular中的工作原理-我认为我们不想重新访问它。我唯一建议的是使用 <ng-template>element而不是,<ng-container>因为它生成的代码更少,不会在DOM等中创建不必要的注释节点:

<ng-template [ngTemplateOutlet]="incomingTemplate" [ngTemplateOutletContext]="{ todo: todo, templateService: libService }">
Run Code Online (Sandbox Code Playgroud)

所以我用ng-template代替了ng-container。

干杯