首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角添加来自另一个指令的fxFlex指令

角添加来自另一个指令的fxFlex指令
EN

Stack Overflow用户
提问于 2017-05-01 12:09:02
回答 1查看 2.3K关注 0票数 6

我试图通过另一个自定义指令添加所有fxFlex fxFlex.gt-xs指令,以便尽可能保持html的干净。我创建了以下指令

代码语言:javascript
复制
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");
    }
}

并按以下方式使用

代码语言:javascript
复制
<div coreFlexInput></div>

但是,在检查dom时,它并不是添加和灵活功能。如果我以这种方式使用它,那么它就起作用了,我希望它能发挥作用。

代码语言:javascript
复制
<div coreFlexInput fxFlex fxFlex-gt-xs="33"></div>

这是正确的做法还是我遗漏了什么?

EN

回答 1

Stack Overflow用户

发布于 2017-05-01 16:02:20

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

下面是最后的dom将是什么样子

这里是plnkr:https://plnkr.co/edit/0UTwoKHVv8ch1zlAdm52

代码语言:javascript
复制
@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() {
  }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43718888

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档