Angular 2 : ng-content attributes passing to child component

标签 angular parameter-passing projection

这样的事情可能吗?

我想通过 ng-content 属性将一个“hasfocus”变量从 cjc-box 传递到 cjc-input 组件。

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

在 ng2 中的投影甚至可能吗?

最佳答案

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

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

这是单向绑定(bind),如果您想要双向绑定(bind),则稍微复杂一些:

  • 添加@Input()装饰器focus盒子组件的属性。
  • 添加@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>

关于 Angular 2 : ng-content attributes passing to child component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671223/

相关文章:

javascript - 在 Javascript 中,为什么需要用 ' ' 包围链接到对象的字符串,但如果它没有链接到对象则不需要?

javascript - 在阿尔伯斯投影 map 上将纬度/经度转换为 X/Y 坐标

binding - 路由器导出的 Angular 2 输出

mysql - Angular 2 & Electron 离线数据

ios - 在 Swift 中启动并将字符串传递给目标 View Controller

c# - 使用 LINQ 进行动态投影

NHibernate 投影 (QueryOver.SelectList) 限制

angular - Angular 分量的绝对或相对 "templateUrls"

javascript - 构建并运行后,是否可以在浏览器中查看以 Angular 声明的 secret 变量?

c - 指向指针数组的指针返回初始地址