【问题标题】:Add attributes to Angular 2 Component Selector向 Angular 2 组件选择器添加属性
【发布时间】:2017-03-16 07:24:07
【问题描述】:

我想为我在 Angular 2 组件实现中创建的自定义选择器添加属性。

@Component({
selector: 'my-node',     // add attributes to this selector 
template: `<div> <ng-content></ng-content> </div>`    
})

这样当我执行&lt;my-node&gt; 时,dom 会生成具有这些额外属性的选择器

&lt;my-node flex="25" layout="row"&gt;

我不想每次都对这些属性进行硬编码&lt;my-node&gt;。我希望这些属性成为选择器构造模板的一部分。

我正在寻找这样的东西,但在 api 中没有看到类似的东西

@Component({
selector: 'my-node',     
selectorAttributes: `layout="row"`  // generates <my-node layout="row">
template: `<div> <ng-content></ng-content> </div>`    
})

【问题讨论】:

  • 你想达到什么目的?为什么不把它们放在模板的根元素上呢?
  • 你试过@HostBinding吗?

标签: angular typescript


【解决方案1】:

使用host@Component 元数据属性。

@Component({
   selector: 'my-node',     // add attributes to this selector 
   template: `<div> <ng-content></ng-content> </div>`,
   host: { // this is applied to 'my-node' in this case
      "[class.some-class]": "classProperty", 
      "[attr.some-attr]": "attrProperty", 
   },   
})

这是一个示例 plunk 。见app/app.component.ts

【讨论】:

  • Adding host: '[attr]="componentProp"' 错误,你能用这个“host:”实现链接到文档吗?
  • 很确定这是我需要的,但仍然出现错误。 Can't bind to 'attr' since it isn't a known property of 'my-node'.
  • If 'my-node' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
  • "[attr]": ''prop" 如果 attr 是像 disabled 这样的本机属性,则可以使用。在其他情况下,请使用 "[attr.yourAttr]": ''prop"
  • 我在答案中添加了一个示例。希望对你有帮助
【解决方案2】:

另一种选择是使用 HostBinding 析取器

@HostBinding('attr.layout')
layout = 'row';

【讨论】:

  • 这个对我很有用。我认为这是最好的解决方案,因为您可以将它放在其他类变量(如输入、输出、私有/公共组件信息等)旁边。它还允许您可预测地设置值并让 Typescript 来分析您的代码评估一个函数作为您的 HostBinding 值。
猜你喜欢
  • 2017-04-04
  • 1970-01-01
  • 2016-07-21
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 2017-01-24
  • 2016-08-03
  • 1970-01-01
相关资源
最近更新 更多