将所有指令传递给组件

时间:2017-10-27 06:13:04

标签: angular angular4-forms

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

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

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

并且对基础<input>的指令具有相同的效果,就像它直接在其上使用一样:

 <input type="text" directive1 directive2 >

UPDATE:

<app-decorated-input>内的内容并不重要,只是它包含<input>这个事实,正如我已经提到的那样。它的模板看起来类似于:

<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>

我想做的就是将<app-decorated-input>上指定的所有指令转移到基础<input>

2 个答案:

答案 0 :(得分:0)

在指令的构造函数中,您可以执行类似的操作。

// process the event in the Main thread.
@Subscribe(threadMode = ThreadMode.MAIN) 
public void onMessageEvent(EventLocation event) {
  // do something with the event.
}

答案 1 :(得分:0)

您可以使每个指令都像使用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);
}