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

Tuk*_*kan 12 javascript typescript angular2-directives angular2-template angular

我有一个组件,我传递模板.在这个组件内部,我想传递上下文,以便我可以显示数据.

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

现在在其他组件中使用组件时:

<my-component>
    <template>
        {{isVisible ? 'yes!' : 'no'}}
    </template>
</my-component>
Run Code Online (Sandbox Code Playgroud)

所以在my-component我传递一个模板,该模板在其类的@ContentChild名称中处理templ.

然后,在my-component传递templ给我的模板中ngTemplateOutlet,另外,我正在传递ngOutletContextisVisible设置为的上下文true.

我们应该yes!在屏幕上看到,但似乎上下文永远不会通过.

我的角度版本:

"@angular/common": "^2.3.1",
"@angular/compiler": "^2.3.1",
"@angular/core": "^2.3.1",
Run Code Online (Sandbox Code Playgroud)

Tuk*_*kan 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 let-isVisible="isVisible">
        {{isVisible ? 'yes!' : 'no'}}
    </template>
</my-component>
Run Code Online (Sandbox Code Playgroud)

循环示例:

@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>
Run Code Online (Sandbox Code Playgroud)

结果:

<div>John</div>
<div>Jacob</div>
Run Code Online (Sandbox Code Playgroud)


Ack*_*ple 8

不推荐使用ngOutletContext并将其重命名为ngTemplateOutletContext.

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

CHANGELOG

  • 那么为什么这被否决了呢?仅仅因为我没有对 CHANGELOG 链接进行短格式处理?我不应该发布有用的信息吗?请帮助我理解,因为我不再提供进一步帮助 (2认同)