【问题标题】:Angular2: Apply any property binding to child elementAngular2:将任何属性绑定应用于子元素
【发布时间】:2016-12-17 20:16:04
【问题描述】:

假设这个简单的 Angular 2 应用程序

主要组件:

@Component({
    selector: "app"
})
@View({
    directives: [ChildComponent]
    template: '<child-component></child-component>'
})
export class App {}

子组件

@Component({
    selector: "child-component",
    template: '<input type="text" id="applyEverythingToMe" />'
})
export class ChildComponent {}

我们如何在不通过 @Attribute, ... 在 ChildComponent 中定义所有内容的情况下将任何属性绑定、指令应用到 applyEverythingToMe 输入字段?

假设例如我们想通过

禁用输入
<child-component [disabled]="true"></child-component>

笨蛋:https://plnkr.co/edit/kndYdGFsp8sEzCPpcKdq?p=preview

编辑:

由于第一个答案错过了我们的实际问题,这里有一点背景:

我们使用 &lt;input type="date" /&gt; 并将香蕉盒中的香蕉分成 () 和 [](例如,此处描述:https://stackoverflow.com/a/39890184/1256072)。 这当然会用 parseDate 混淆每个组件,而且我们不能使用[(ngModel)] 也很烦人。 因为我们没有找到任何方法将 ngModel 指令扩展到例如myModelDate 自动拆分 [()] 并应用 parse 方法,我们创建了自己的组件来实现 ControlValueAccessor,因此我们可以将它与 [(ngModel)] 绑定。此组件模板仅包含这一输入 type=date 字段。我们现在希望我们自己的组件的行为与任何其他输入一样,因此我们可以简单地使用&lt;my-date [disabled]="true"/&gt;&lt;my-date [attr.whatever]="something" /&gt;,而无需通过@Input@Attribute、...显式定义所有属性。

【问题讨论】:

  • 我建议您完成《英雄之旅》教程,然后如果您还有问题,请重新提问。本教程将为您解答这个问题 - 以及更多问题。
  • 不,不幸的是它没有。我编辑了我最初的问题,以提供更多背景知识我们正在努力实现的目标。
  • @View({ 大约在 9 个月前被删除。你用的是哪个 Angular2 版本?
  • 我觉得你的问题很混乱,我完全不清楚这个问题是关于什么的。

标签: angular


【解决方案1】:

在要在子组件中公开的属性上使用 @Input() 装饰器。

例如:

import {Component, Input } from '@angular/core';

@Component({
    selector: "child-component",
    template: '<input type="text" />'
})
export class ChildComponent {
  @Input disabled: boolean;
}

【讨论】:

  • 这正是我们试图避免的。
猜你喜欢
  • 2013-05-31
  • 1970-01-01
  • 2018-10-21
  • 2021-02-25
  • 2016-10-25
  • 2017-08-10
  • 2011-02-23
  • 1970-01-01
  • 2015-09-28
相关资源
最近更新 更多