Shortcut for passing child as template to parent

106 views
Skip to first unread message

frabbit

unread,
Jan 17, 2020, 5:36:39 AM1/17/20
to Angular and AngularJS discussion
Hello community, 

I currently looking for a way to cut the noise when passing templates to components 

Consider the following code:

```
<parent>
  <ng-template #child1><div>Test</div></ng-template>
  <ng-template #child2><div>Test</div></ng-template>
</parent>
```

is it possible to create a structural directive that can be used like this or similar?

```
<parent>
  <div *asTemplate="#child1">Test</div>
  <div *asTemplate="#child2">Test</div>
</parent>
```

so that 

```
  <div *asTemplate="#child1">Test</div>
```

desugars to 

```
<ng-template #child1><div>Test</div></ng-template>
```


Directly using

<div *asTemplate #child1>Test</div>

doesn't work of course. because the ref is part of the div.


Thx a lot!


frabbit

unread,
Jan 17, 2020, 5:39:13 AM1/17/20
to Angular and AngularJS discussion
I know that i could use @ContentChildren to achieve something similar, but i would prefer just sugar for `<ng-template #child><div>Test</div><ng-template>`.

Sander Elias

unread,
Jan 17, 2020, 7:51:59 AM1/17/20
to Angular and AngularJS discussion
Hi Frabbit,

Yes, not a problem. You can do something like this:
<div *myTemplate #child1>...</div>

and the div will end up in the template.

Regards
Sander

frabbit

unread,
Jan 17, 2020, 8:06:49 AM1/17/20
to Angular and AngularJS discussion
Hmm, thx 

thx, but i cannot catch the templateRef via 


@ContentChild('a', { read:TemplateRef, static:false }) a: TemplateRef<any>;

inside of parent. And this works fine in my desugared version.

frabbit

unread,
Jan 17, 2020, 8:09:50 AM1/17/20
to Angular and AngularJS discussion
Sorry there was a typo, it should have been:

@ContentChild('child', { read:TemplateRef, static:false }) myChild: TemplateRef<any>;

Sander Elias

unread,
Jan 17, 2020, 8:11:14 AM1/17/20
to Angular and AngularJS discussion
Hi Frabbit,

That makes sense, as you should be doing something like:
@ContentChild(myTemplate, { read:TemplateRef, static:false }) myTemplate: TemplateRef<any>;
and inject myTemplate in the constructor.

Regards
Sander

frabbit

unread,
Jan 17, 2020, 8:20:12 AM1/17/20
to Angular and AngularJS discussion
But this only works if i have one child, to pass exactly two for example i would love to do:

@ContentChild('a', { read:TemplateRef, static:false }) myTemplate: TemplateRef<any>;
@ContentChild('b', { read:TemplateRef, static:false }) myTemplate: TemplateRef<any>;


instead of using @ContentChildren.
Reply all
Reply to author
Forward
0 new messages