0

I would like to add the make-col mixin defined by Bootstrap with the Angulars Renderer2.

Context

The idea is to create a directive that receives two inputs:

  • The number of columns the element should use
  • The total amount of columns

And adds the mixin to the element.

Code

In an ideal world it would look something like this:


@Directive({
    selector: '[appCustomColumn]'
})
export class CustomColumnDirective implements OnInit {

    @Input()
    public amountOfColumns: number;

    @Input()
    public totalAmountOfColumns: number;

    constructor(private elementRef: ElementRef,
                private renderer: Renderer2) {
    }

    public ngOnInit(): void {
        // This API does not exist
        this.renderer.setMixin(this.elementRef.nativeElement, '@include make-col(' + this.amountOfColumns  + ',' + this.totalAmountOfColumns + ')');
    }
}

Question Does anyone know if you can apply a mixin through the renderer2 in Angular or if there is another way to do this?

R. de Ruijter
  • 513
  • 5
  • 13

1 Answers1

2

Your SASS code is compiled when you build your app and not while your app is running. You can't provide SASS code dynamically at runtime, only CSS.

Check the source code to see what CSS the mixin adds. Then add the CSS.

@Directive({
  selector: "[appCustomColumn]"
})
export class CustomColumnDirective {
  @Input() amountOfColumns: number;
  @Input() totalAmountOfColumns: number;

  constructor(private el: ElementRef, private renderer: Renderer2) {}

  ngOnChanges(changes: SimpleChanges) {
    this.renderer.setStyle(
      this.el.nativeElement,
      "flex",
      "1 1 " + this.percentage(this.amountOfColumns / this.totalAmountOfColumns)
    );
    this.renderer.setStyle(
      this.el.nativeElement,
      "max-width",
      this.percentage(this.amountOfColumns / this.totalAmountOfColumns)
    );
  }

  private percentage(n: number): string {
    return Math.floor(n * 100) + "%";
  }
}
frido
  • 13,065
  • 5
  • 42
  • 56