Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Setting context with createEmbeddedView

I'm having a hard time trying to pass context data to my dynamicly created embeded view.

Note: I'm using Angular 2.4.7

Here is what i whant to achieve:


In my DialogPresetComponent (dialog-preset.component.html):

This component's view contain a bunch of template ready to be used within my dialog framework:

<template #presetInfo>
   {{options.description}} // Note this binding ! Here is the problem
</template>

Still in this component, i get a ref to those templates like this:

@ViewChild('presetInfo', { read: TemplateRef }) presetInfo: TemplateRef<any>;

Then, i store this templateRef in a DialogService, so i can access them later, and from somewhere else.


In DialogComponent (dialog.component.html):

Here is the template of my modal:

<div class='c-header'>
</div>
<div class='c-body'>
    <div #container></div>
</div>
<div class='c-footer'>
</div>

In DialogComponent (dialog.component.ts):

In my DialogComponent grab a reference to the container like this:

@ViewChild('container', {read: ViewContainerRef }) containerRef: ViewContainerRef;

I also define attributes that i want to access from my dynamicly injected template:

options: DialogOptions = { title: 'Dialog title' };

What am i trying to do:

I'm trying to put the template #presetInfo within the #container and with the context of my DialogComponent

So finaly, i inject my template in my component giving it the right context:

In my DialogComponent (dialog.component.ts):

// Where templateRef is the template previously  defined in DialogPresetComponent
createEmbeddedView( templateRef: TemplateRef<any> ) {
    this.containerRef.createEmbeddedView( templateRef, this );    
}

The problem come from the fact that the binding {{options.description}} in my injected template DO NOT WORK, even when passing the right context ('this' in my case) via createEmbeddedView.

The framework tell me that options is undefined.

What am i missing here ?

There is not a lot of documentation about this 'context' stuff, so i guess i'm not doing it the right way ....

Any clues or hints are welcome !

Thanks !

like image 835
Clement Avatar asked Feb 23 '17 16:02

Clement


1 Answers

this.containerRef.createEmbeddedView( templateRef, {$implicit: {description: 'some description'} } );    
<template #presetInfo let-options>
   {{options.description}} // Note this binding ! Here is the problem
</template>

If you pass an object with a property $implicit then just let-xxx is enough to make the $implicit value available as xxx within the template.

For other properties you need let-yyy="someProp" to make it available within the template as yyy.

like image 195
Günter Zöchbauer Avatar answered Oct 04 '22 22:10

Günter Zöchbauer