本文介绍了Angular2:ng-content属性传递给子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样可能吗?

我想通过ng-content属性将csc-box中的"hasfocus"变量传递给cjc-input组件.

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

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}}" />

使用ng2中的投影甚至有可能吗?

Is this even possible with projections in ng2?

推荐答案

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

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:

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

这篇关于Angular2:ng-content属性传递给子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-02 21:18