import { Directive, Input, ElementRef, HostBinding, OnInit } from '@angular/core'; @Directive({ selector: '[farris-row]', }) export class FarrisRowDirective implements OnInit { @Input() type: string = 'flex'; @Input() gutter: number = 16; @Input() justify: string = 'start'; @Input() align: string = 'start'; /** * xs={ * justify:'start', * align:'start' * } */ @Input() xs: any; @Input() sm: any; @Input() md: any; @Input() lg: any; @Input() xl: any; @HostBinding('class') get respClass() { return `${this.getJustifyClass()}${this.getAlignClass()}${this.getGutterClass()}${this.getBreakpointClass()}`; } // 绑定row 到class @HostBinding('class.row') isRow = this.type === 'flex'; // nativeClass: string = ''; constructor(private el: ElementRef) { // 初始化类名 添加宿主元素已有的类名 this.nativeClass += this.el.nativeElement.classList.value; } ngOnInit() { } // 获取justify class getJustifyClass() { const justifyStr = this.justify !== 'start' ? ` justify-content-${this.justify}` : ' '; return `${this.nativeClass}${justifyStr}`; } // 获取 align class getAlignClass() { return this.align !== 'start' ? ` align-items-${this.align}` : ' '; } // 响应式 justify getBreakpointClass() { const makeClass = (breakpoint: string): string => { const props = this[breakpoint] || {}; // 获取对象中 justify或者align return Object.keys(props).map(prop => prop === 'justify' ? `justify-content-${breakpoint}-${props[prop]}` : `align-items-${breakpoint}-${props[prop]}`).join(' '); }; const classStr = ['sm', 'md', 'lg', 'xl'].reduce((pre, current) => { return `${pre} ${makeClass(current)}`; }, ''); return classStr; } // 有无间隔 getGutterClass() { return !this.gutter ? ' no-gutters' : ' '; } }