从父指令向子节点添加指令

时间:2018-04-26 10:58:58

标签: angular

在AngularJS中,我们曾经拥有prepost函数,并且能够在需要时使用$compile模板。在Angular(2 +)中无法做到这一点,是吗?

具体来说,我想要实现的是,拥有这样的模板:

<form myDirective>
    <input type="text" />
    <input type="text" />
</form>

myDirective动态地将另一个指令(比如anotherDirective)添加到input类型的所有主机的子项中。这有可能吗?

1 个答案:

答案 0 :(得分:3)

不,不可能。您无法动态分配指令,无论是在另一个指令中还是在完整组件中(组件被视为带有Angular模板的指令)。

动态操作硬(例如不是CSS)DOM属性的唯一方法是使用Renderer2并在myDirective中访问主机的元素,如下所示:

constructor(private hostEl: ElementRef){}
ngOnInit() {
    if(hostEl.nativeElement.children.length) { 
        hostEl.nativeElement.children.forEach(el => {if (isInput(el) { useRenderer2InSomeWay(el) })})
    }
}

但我要做的是直接在每个输入中放置anotherDirective,这样你就不必访问孩子或者(甚至更好)考虑根本不使用指令而只是定义一个包装器<input>的组件:

        <my-input-wrapper
          <input
            [config]="someConfigToApplyToInputInside"
            [formControlName]="'foobar'">
          </input>
        </my-input-wrapper>

并在MyInputWrapperComponent中:

@ContentChildren('input') inputs: QueryList<any>;

使用ContentChild / ContentChildren,您可以从周围的组件访问FormControls,但仍然可以将输入中的自定义占位符和图标等ui-stuff委托给包装器组件。