10

Is something like this possible?

I want to pass an "hasfocus" variable from cjc-box through ng-content attributes to the cjc-input component.

app.component.html

<div cjc-box><div cjc-input></div></div>

cic-box.component.html

<div class="cjc-box">
  <div><ng-content hasfocus="focus"></ng-content></div>
</div>

cic-input.component.html

<input class="cjc-input" type="text" focus="{{hasfocus}}" />

Is this even possible with projections in ng2?

Christoph Janik
  • 103
  • 1
  • 4

1 Answers1

8

It is possible to pass variable to projected content (assuming component cjc-box declares property focus and component cjc-input declares property hasfocus):

<div cjc-box #box><div cjc-input [hasfocus]="box.focus"></div></div>

This is one-way binding, if you want two-way it is slightly more complex:

  • Add @Input() decorator to focus property of box component.
  • Add @Input() decorator to hasfocus property of input component
  • Add @Output() hasfocusChange:EventEmitter<any> = new EventEmitter<any>(); to input component.
  • Add this.hasfocusChange.emit(this.hasfocus); after hasfocus change in your input component.
  • Change template to <div cjc-box #box><div cjc-input [(hasfocus)]="box.focus"></div></div>
kemsky
  • 14,727
  • 3
  • 32
  • 51
  • That was easy! Thank you! – Christoph Janik Apr 17 '16 at 13:11
  • Now i get the value for hasfocus in the cjc-input component, great! But when i change the value inside the cjc-input component then its not changing in parent component (cjc-box). It looks as if it would be a copy rather than a reference. :( – Christoph Janik Apr 17 '16 at 14:16
  • 1
    Could you explain why this is necessary: "Add @Input() decorator to focus property of box component." – hgoebl Jan 11 '17 at 09:25