How to use the EmbeddedViewRef context variable

I'm a little unsure how to use a variable EmbeddedViewRef context. From what I collect from Angular 2 changelog, the variable contextreplaces the methods setLocaland getLocalas a mechanism for setting local variables in the inline view.

After looking at this blog post in which setLocalI am using , I put 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 {}

Here you can find the plunker for this example here . When the list displays, each of the list items is empty. Am I thinking about the contextwrong way or will I install it incorrectly? If yes, let me know.

+4
source share
1

:

:

  <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

+5

Source: https://habr.com/ru/post/1652557/


All Articles