简体   繁体   English

Angular2:传递给子组件的ng-content属性

[英]Angular2: ng-content attributes passing to child component

Is something like this possible? 这样的事情可能吗?

I want to pass an "hasfocus" variable from cjc-box through ng-content attributes to the cjc-input component. 我想将一个“hasfocus”变量从cjc-box传递到ng-content属性到cjc-input组件。

app.component.html app.component.html

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

cic-box.component.html CIC-box.component.html

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

cic-input.component.html CIC-input.component.html

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

Is this even possible with projections in ng2? 这对于ng2中的预测是否可能?

It is possible to pass variable to projected content (assuming component cjc-box declares property focus and component cjc-input declares property hasfocus ): 可以将变量传递给投影内容(假设组件cjc-box声明属性focus ,组件cjc-input声明属性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. @Input()装饰器添加到box组件的focus属性。
  • Add @Input() decorator to hasfocus property of input component @Input()装饰器添加到输入组件的hasfocus属性
  • Add @Output() hasfocusChange:EventEmitter<any> = new EventEmitter<any>(); 添加@Output() hasfocusChange:EventEmitter<any> = new EventEmitter<any>(); to input component. 输入组件。
  • Add this.hasfocusChange.emit(this.hasfocus); 添加this.hasfocusChange.emit(this.hasfocus); after hasfocus change in your input component. 在输入组件中更改hasfocus之后。
  • Change template to <div cjc-box #box><div cjc-input [(hasfocus)]="box.focus"></div></div> 将模板更改为<div cjc-box #box><div cjc-input [(hasfocus)]="box.focus"></div></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM