Atu*_*ary 6 angular-material2 angular-flex-layout angular
我正在尝试通过另一个自定义指令添加所有 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");
}
}
Run Code Online (Sandbox Code Playgroud)
并按如下方式使用它
<div coreFlexInput></div>
Run Code Online (Sandbox Code Playgroud)
但在检查 dom 时,它并没有添加和弯曲功能。如果我以这种方式使用它,那么它就可以正常工作,这是我所期望的
<div coreFlexInput fxFlex fxFlex-gt-xs="33"></div>
Run Code Online (Sandbox Code Playgroud)
这是正确的方法还是我错过了什么?
我认为您无法在不通过编译器步骤的情况下动态添加指令,这只是一个过于复杂的过程。我遇到了同样的问题,最终我创建了一个包含所有必需指令的新容器,并将内容从原始父级删除到新容器。
这是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() {
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2615 次 |
| 最近记录: |