5

我正在尝试通过另一个自定义指令添加所有 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>

这是一个正确的方法还是我错过了什么?

4

1 回答 1

3

我不认为您可以在不通过编译器步骤的情况下动态添加指令,这只是一个过于复杂的过程。我遇到了同样的问题,最终我创建了一个包含所有必需指令的新容器,并将内容从原始父级删除到一个新容器。

这是最终 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() {
  }
}
于 2017-05-01T16:02:20.770 回答