【问题标题】:Passing on all directives to a child element of the component将所有指令传递给组件的子元素
【发布时间】:2018-04-08 16:14:14
【问题描述】:

我有一些自定义指令,它们基本上是为<input> 设计的。 我有一个自定义组件<app-decorated-input>

在我的应用程序中有大量的<app-decorated-input>s 和简单的<input>s,其中一些我喜欢使用指令,而另一些我不喜欢。当这样使用指令时,如何将指令传递给底层<input>

<app-decorated-input directive1 directive2 ></app-decorated-input>

并且对底层&lt;input&gt; 具有相同的指令效果,就好像直接在其上使用它一样:

 <input type="text" directive1 directive2 >

更新:

&lt;app-decorated-input&gt; 内部的内容并没有太大的相关性,只是它包含一个 &lt;input&gt;,正如我已经提到的那样。它的模板看起来类似于:

<div> Some decorations here </div>
<div> 
  <input type="text" {...directives}> <!-- In ReactJS this is done by using {...this.props} -->
</div>
<div> Some decorations here too! </div>

我要做的就是将&lt;app-decorated-input&gt; 上指定的所有指令转移到底层&lt;input&gt;

【问题讨论】:

  • 您找到解决方案了吗?
  • 你有想过这个吗?
  • @dcp3450,还没有

标签: angular angular4-forms


【解决方案1】:

您可以让每个指令都像使用 ControlValueAccessor 或验证器一样提供自己

export const MY_DIRECTIVES = new InjectionToken<any>('MyDirectives');
export const MY_DIRECTIVE1: Provider = {
  provide: MY_DIRECTIVES,
  useExisting: forwardRef(() => MyDirective1),
  multi: true
};

@Directive({
  selector: '....',
  providers: [MY_DIRECTIVE1]
})
class MyDirective1 {}

然后在你的输入组件中

constructor(@Optional() @Self() @Inject(MY_DIRECTIVES) private myDirectives: any[]) {
  console.log(myDirectives);
}

【讨论】:

  • 你能详细说明一下吗?如果我在我的自定义组件构造函数中添加它,我会遇到循环依赖问题。还是您在谈论本机 Input 元素?那么如何传递给constructor呢?
  • 我建议您使用导致错误的代码创建一个新问题。
  • 好吧,问题基本相同,只是使用离子输入(来自 ionic2)而不是输入。我不认为这与错误有关,我只是不知道该把它放在哪里。
【解决方案2】:

在指令的构造函数中你可以做一些类似的事情。

constructor(
    @Attribute('attributeName') private attributeUno:String, 
    private element:ElementRef
) {
    console.log(this.attributeUno);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2019-10-04
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多