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.
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 {}
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:
cannonical form:
<template foo let-bar="bar" let-baz="baz" let-qux="qux" >
<ul>
<li>{{bar}}</li>
<li>{{baz}}</li>
<li>{{qux}}</li>
</ul>
</template>
short form:
<div *foo="let bar=bar let baz=baz let qux=qux">
<ul>
<li>{{bar}}</li>
<li>{{baz}}</li>
<li>{{qux}}</li>
</ul>
</div>
Plunker example
See also ng-content select bound variable
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With