How to use an EmbeddedViewRef's context variable

醉酒当歌 提交于 2020-05-13 04:49:33

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/39159302/how-to-use-an-embeddedviewrefs-context-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!