问题
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?
回答1:
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 tofocusproperty of box component. - Add
@Input()decorator tohasfocusproperty of input component - Add
@Output() hasfocusChange:EventEmitter<any> = new EventEmitter<any>();to input component. - Add
this.hasfocusChange.emit(this.hasfocus);afterhasfocuschange in your input component. - Change template to
<div cjc-box #box><div cjc-input [(hasfocus)]="box.focus"></div></div>
来源:https://stackoverflow.com/questions/36671223/angular2-ng-content-attributes-passing-to-child-component