import { Directive, Input, ElementRef, HostBinding } from '@angular/core'; @Directive({ selector: '[farris-col]' }) export class FarrisColDirective { // col @Input() col: boolean; @Input('col-sm') colSm: boolean; @Input('col-md') colMd: boolean; @Input('col-lg') colLg: boolean; @Input('col-xl') colXl: boolean; @Input() span: number = 0; // 向右移动几个col @Input() offset: number = 0; // order col顺序 @Input() order: number; // <576 @Input() xs: any; // >=576 @Input() sm: any; // >=768 @Input() md: any; // >=960 @Input() lg: any; // >=1200 @Input() xl: any; @HostBinding('class') get ColClass() { return `${this.nativeClass} ${this.getSpanClass()}${this.getBreakpointClass()}${this.getOffsetClass()}${this.getOrderClass()}`; } @HostBinding('class.col') get isCol() { return this.col; } @HostBinding('class.col-sm') get isColSm() { return this.colSm; } @HostBinding('class.col-md') get isColMd() { return this.colMd; } @HostBinding('class.col-lg') get isColLg() { return this.colLg; } @HostBinding('class.col-xl') get isColXl() { return this.colXl; } nativeClass = ''; constructor(private el: ElementRef) { this.nativeClass += this.el.nativeElement.classList.value; } /* 获取span 类名 */ getSpanClass() { return this.span ? ` col-${this.span}` : ` `; } /* 获取响应式 类名 xs sm md lg xl 可以是数字,代表span;也可以是对象,内部包含span offset*/ getBreakpointClass() { const makeClass = (breakpoint: string): string => { const props = this[breakpoint] || {}; // 获取对象中 span或者offset return Object.keys(props).map(prop => prop === 'span' ? `col-${breakpoint}-${props[prop]}` : prop === 'offset' ? `offset-${breakpoint}-${props[prop]}` : `order-${breakpoint}-${props[prop]}`).join(' '); }; return ['sm', 'md', 'lg', 'xl'].reduce((pre, current) => { return typeof this[current] === 'object' ? `${pre} ${makeClass(current)}` : typeof this[current] === 'number' ? `${pre} col-${current}-${this[current]}` : `${pre} `; }, ''); } /* 获取offset */ getOffsetClass() { return this.offset ? ` offset-${this.offset}` : ` `; } // get order class getOrderClass() { return this.order ? ` order-${this.order}` : ` `; } }