Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use an EmbeddedViewRef's context variable

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.

like image 206
lewistg Avatar asked Aug 26 '16 06:08

lewistg


1 Answers

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

like image 96
Günter Zöchbauer Avatar answered Oct 05 '22 22:10

Günter Zöchbauer