Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular add fxFlex directive from another directive

I am trying to add all fxFlex fxFlex.gt-xs directive via another custom directive so that I can keep my html as clean as possible. I have created the following directive

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");
    }
}

and using it as below

<div coreFlexInput></div>

But it is not adding and flex functionality when inspecting the dom. If I use it this way then it is working which I expect anyways

<div coreFlexInput fxFlex fxFlex-gt-xs="33"></div>

Is it a right approach or am I missing something?

like image 252
Atul Chaudhary Avatar asked Oct 18 '22 13:10

Atul Chaudhary


1 Answers

I don't think you can add directives dynamically without going via Compiler steps and it is just one overly complicated process. I had the same issue and what I ended up with creating a new container with all required directives and removing the content from original parent to a new one.

here is how the final dom will look likeenter image description here

here is 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() {
  }
}
like image 58
Julia Passynkova Avatar answered Nov 11 '22 13:11

Julia Passynkova