我试图通过另一个自定义指令添加所有fxFlex fxFlex.gt-xs指令,以便尽可能保持html的干净。我创建了以下指令
import { Directive, ElementRef, Renderer, OnInit } from '@angular/core';
@Directive({
selector: '[coreFlexInput]'
})
export class FlexInputDirective implements OnInit {
constructor(private el: ElementRef, private renderer: Renderer) {
// Use renderer to render the element with 50
}
ngOnInit() {
this.renderer.setElementAttribute(this.el.nativeElement, "fxFlex", "");
this.renderer.setElementAttribute(this.el.nativeElement, "fxFlex.gt-xs", "33");
this.renderer.setElementClass(this.el.nativeElement, "padding-5", true);
this.renderer.setElementStyle(this.el.nativeElement, "line-height", "50px");
this.renderer.setElementStyle(this.el.nativeElement, "vertical-align", "middle");
}
}并按以下方式使用
<div coreFlexInput></div>但是,在检查dom时,它并不是添加和灵活功能。如果我以这种方式使用它,那么它就起作用了,我希望它能发挥作用。
<div coreFlexInput fxFlex fxFlex-gt-xs="33"></div>这是正确的做法还是我遗漏了什么?
发布于 2017-05-01 16:02:20
我认为您不能在不经过编译器步骤的情况下动态添加指令,这只是一个过于复杂的过程。我也遇到了同样的问题,我最终创建了一个包含所有必需指令的新容器,并将内容从原始父容器移到了一个新容器。
下面是最后的dom将是什么样子

这里是plnkr:https://plnkr.co/edit/0UTwoKHVv8ch1zlAdm52
@Directive( {
selector: '[anotherDir]'
})
export class AnotherDir {
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
this.el.nativeElement.style.color = 'blue';
}
}
@Component({
selector: '[parent]',
template:
`
<ng-template #tpl>
<div anotherDir><ng-content></ng-content></div>
</ng-template>
`
})
export class Parent {
@ViewChild('tpl') tpl: TemplateRef<any>;
constructor(private vc: ViewContainerRef) {
}
ngAfterViewInit() {
this.vc.createEmbeddedView(this.tpl);
}
}
@Component({
selector: 'my-app',
template: `
<div>
<div parent>
here is the content
</div>
</div>
`,
})
export class App {
constructor() {
}
}https://stackoverflow.com/questions/43718888
复制相似问题