通过 Angular2 中的 ngOutletContext 将上下文传递给模板

Passing context to template through ngOutletContext in Angular2

我有一个要向其传递模板的组件。在此组件内部,我想传递上下文以便显示数据。

@Component({
  selector: 'my-component',
  providers: [],
  template: `
    <template [ngTemplateOutlet]="templ" [ngOutletContext]="{isVisible: true}">
    </template>
  `
})
export class MyElementComponent implements OnInit {
    @ContentChild(TemplateRef) templ;
    constructor(){}
}

现在在其他组件内部使用组件时:

<my-component>
    <template>
        {{isVisible ? 'yes!' : 'no'}}
    </template>
</my-component>

因此,在 my-component 中,我传递了一个模板,该模板由 @ContentChild 在 class 中处理,名称为 templ

然后,在 my-component 的模板中,我将 templ 传递给 ngTemplateOutlet,另外,我使用 ngOutletContext 传递上下文,其中 isVisible设置为 true.

我们应该在屏幕上看到 yes!,但似乎从未传递上下文。

我的angular版本:

"@angular/common": "^2.3.1",
"@angular/compiler": "^2.3.1",
"@angular/core": "^2.3.1",

好久没搞定了

单值示例:

@Component({
  selector: 'my-component',
  providers: [],
  template: `
    <template [ngTemplateOutlet]="templ" [ngOutletContext]="{isVisible: true}">
    </template>
  `
})
export class MyElementComponent implements OnInit {
    @ContentChild(TemplateRef) templ;
    constructor(){}
}

<my-component>
    <template let-isVisible="isVisible">
        {{isVisible ? 'yes!' : 'no'}}
    </template>
</my-component>

循环示例:

@Component({
  selector: 'my-component',
  providers: [],
  template: `
    <div *ngFor="let element of data">
        <template [ngTemplateOutlet]="templ" [ngOutletContext]="{element: element}">
        </template>
    </div>
  `
})
export class MyElementComponent implements OnInit {
    @ContentChild(TemplateRef) templ;
    constructor(){
        this.data = [{name:'John'}, {name:'Jacob'}];
    }
}

--- 

<my-component>
    <template let-element="element">
        {{element.name}}
    </template>
</my-component>

结果:

<div>John</div>
<div>Jacob</div>

注意 ngOutletContext 已弃用并重命名为 ngTemplateOutletContext。

在更改日志中搜索 "NgTemplateOutlet#ngTemplateOutletContext"

CHANGELOG