如何使用EmbeddedViewRef的上下文变量 [英] How to use an EmbeddedViewRef's context variable
问题描述
我不太确定如何使用EmbeddedViewRef
的context
变量.从我从Angular 2的变更日志中收集到的信息来看,context
变量取代了setLocal
和getLocal
方法,作为在嵌入式视图中设置局部变量的机制.
I am a little unsure how to use the EmbeddedViewRef
's context
variable. From what I gather from Angular 2's changelog, the context
variable replaces the setLocal
and getLocal
methods as the mechanism for setting local variables in an embedded view.
查看此博客文章后(使用setLocal
),我整理了以下最小示例:
After looking at this blog post, which uses setLocal
, I have pieced together the following minimal example:
import { Directive, TemplateRef, ViewContainerRef } from '@angular/core'
export class FooTemplateContext {
constructor(public bar: string, public baz: string, public qux: string) {}
}
@Directive({
selector: '[foo]'
})
export class Foo {
constructor(viewContainerRef: ViewContainerRef, templateRef: TemplateRef<FooTemplateContext>) {
let context = new FooTemplateContext('bar', 'baz', 'qux');
let view = viewContainerRef.createEmbeddedView(templateRef, context);
}
}
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { Foo } from './foo.directive'
@Component({
selector: 'my-app',
template: `
<div>
<div *foo>
<ul>
<li>{{bar}}</li>
<li>{{baz}}</li>
<li>{{qux}}</li>
</ul>
</div>
</div>
`,
directives: [Foo]
})
export class App {
constructor() {}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
可以在此处找到该示例的插件.列表呈现时,每个列表项均为空.我是否以错误的方式考虑context
或设置不当?如果是这样,请告诉我.
A plunker for this example can be found here. When the list renders, each of the list items are empty. Am I thinking of the context
in the wrong way or setting it improperly? If so, please let me know.
推荐答案
您需要声明变量并将上下文的属性分配给它们:
You need to declare variables and assign properties of the context to them:
规范形式:
<template foo let-bar="bar" let-baz="baz" let-qux="qux" >
<ul>
<li>{{bar}}</li>
<li>{{baz}}</li>
<li>{{qux}}</li>
</ul>
</template>
简写:
<div *foo="let bar=bar let baz=baz let qux=qux">
<ul>
<li>{{bar}}</li>
<li>{{baz}}</li>
<li>{{qux}}</li>
</ul>
</div>
另请参见 ng-content选择绑定变量
这篇关于如何使用EmbeddedViewRef的上下文变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!