【问题标题】:Passing context to template through ngOutletContext in Angular2通过Angular2中的ngOutletContext将上下文传递给模板
【发布时间】:2017-05-07 12:10:28
【问题描述】:

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

@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 在其类中处理,名称为templ

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

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

我的角度版本:

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

【问题讨论】:

  • 我面临同样的问题。你是对的,上下文永远不会传递。这是因为您作为内容传递给 的模板实际上已绑定到 主机的上下文。我也想让它工作,但我还没有看到任何方法。
  • @AlexanderLeonov 看看我的回答。我找到了。

标签: javascript angular typescript angular2-template angular2-directives


【解决方案1】:

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

在更改日志中搜索“NgTemplateOutlet#ngTemplateOutletContext”

CHANGELOG

【讨论】:

  • 那么为什么这被否决了?只是因为我没有缩短 CHANGELOG 链接的格式?我不应该发布有用的信息吗?请帮助我理解,因为我不想提供进一步的帮助
  • 我的原始评论已被投票。鼓励再次提供帮助!
【解决方案2】:

经过很长时间,我做到了。

单值示例:

@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>

【讨论】:

    猜你喜欢
    • 2019-09-19
    • 2016-06-29
    • 1970-01-01
    • 2014-11-11
    • 2013-09-15
    • 1970-01-01
    • 2021-09-10
    • 2013-09-27
    • 1970-01-01
    相关资源
    最近更新 更多