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

Chr*_*nik 9 projection parameter-passing angular

这样的事情可能吗?

我想将一个"hasfocus"变量从cjc-box传递到ng-content属性到cjc-input组件.

app.component.html

<div cjc-box><div cjc-input></div></div>
Run Code Online (Sandbox Code Playgroud)

CIC-box.component.html

<div class="cjc-box">
  <div><ng-content hasfocus="focus"></ng-content></div>
</div>
Run Code Online (Sandbox Code Playgroud)

CIC-input.component.html

<input class="cjc-input" type="text" focus="{{hasfocus}}" />
Run Code Online (Sandbox Code Playgroud)

这对于ng2中的预测是否可能?

kem*_*sky 8

可以将变量传递给投影内容(假设组件cjc-box声明属性focus和组件cjc-input声明属性hasfocus):

<div cjc-box #box><div cjc-input [hasfocus]="box.focus"></div></div>
Run Code Online (Sandbox Code Playgroud)

这是单向绑定,如果你想要双向绑定,它会稍微复杂一些:

  • @Input()装饰器添加到focusbox组件的属性中.
  • @Input()装饰器添加到hasfocus输入组件的属性
  • 添加@Output() hasfocusChange:EventEmitter<any> = new EventEmitter<any>();到输入组件.
  • 在输入组件中更改this.hasfocusChange.emit(this.hasfocus);后添加hasfocus.
  • 将模板更改为 <div cjc-box #box><div cjc-input [(hasfocus)]="box.focus"></div></div>