@angular/core#Directive TypeScript Examples

The following examples show how to use @angular/core#Directive. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: scroll-to.directive.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
@Directive({
  selector: '[appScrollTo]',
})
export class ScrollToDirective {
  @Input() target = '';
  @HostListener('click')
  onClick() {
    const targetElement = document.querySelector(this.target);
    targetElement.scrollIntoView({ behavior: 'smooth' });
  }

  constructor() {}
}
Example #2
Source File: table-cell.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
/** Cell template container that adds the right classes and role. */
@Directive({
  // eslint-disable-next-line @angular-eslint/directive-selector
  selector: 'aui-table-cell',
  host: {
    class: 'aui-table__cell',
    role: 'gridcell',
    '[class.aui-table__cell--column]': 'direction === "column"',
  },
})
export class TableCellDirective extends CdkCell {
  @Input()
  direction: 'row' | 'column' = 'row';

  constructor(columnDef: CdkColumnDef, elementRef: ElementRef<HTMLElement>) {
    super(columnDef, elementRef);
    elementRef.nativeElement.classList.add(
      bem.element(`column-${columnDef.cssClassFriendlyName}`),
    );
  }
}
Example #3
Source File: url-validator.directive.ts    From one-platform with MIT License 6 votes vote down vote up
@Directive({
  selector: '[urlValidator][ngModel]',
  providers: [
    { provide: NG_VALIDATORS, useExisting: UrlValidatorDirective, multi: true },
  ],
})
export class UrlValidatorDirective {
  validator: ValidatorFn;
  constructor() {
    this.validator = this.urlValidator();
  }

  validate(c: FormControl) {
    return this.validator(c);
  }

  urlValidator(): ValidatorFn {
    return (control: FormControl) => {
      const url = control.value;
      try {
        new URL(url);
        return null;
      } catch (e) {
        return { urlValidator: { valid: false } };
      }
    };
  }
}
Example #4
Source File: tab-body.component.ts    From alauda-ui with MIT License 6 votes vote down vote up
/** Used to flag tab labels for use with the portal directive */
@Directive({
  selector: '[auiTabLabel]',
})
export class TabLabelDirective extends CdkPortal {
  // eslint-disable-next-line @typescript-eslint/no-useless-constructor
  constructor(
    templateRef: TemplateRef<any>,
    viewContainerRef: ViewContainerRef,
  ) {
    super(templateRef, viewContainerRef);
  }
}
Example #5
Source File: ion-intl-tel-input.directive.ts    From ion-intl-tel-input with MIT License 6 votes vote down vote up
@Directive({
  // tslint:disable-next-line: directive-selector
  selector: '[ionIntlTelInputValid]',
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: IonIntlTelInputValidatorDirective,
      multi: true,
    },
  ],
})
export class IonIntlTelInputValidatorDirective implements Validator {
  validate(control: AbstractControl): ValidationErrors | null {
    return IonIntlTelInputValidators.phone(control);
  }
}
Example #6
Source File: scroll-down.directive.ts    From t3mpl-editor with MIT License 6 votes vote down vote up
@Directive({
	selector: '[appScrollDown]'
})
export class ScrollDownDirective implements OnChanges {

	@Input()
	public follow: any;

	public constructor(
		private readonly el: ElementRef<HTMLElement>) {
	}

	public ngOnChanges() {
		setTimeout(() => {
			this.el.nativeElement.scrollTop = this.el.nativeElement.scrollHeight;
		});
	}
}
Example #7
Source File: dialog-close.directive.ts    From alauda-ui with MIT License 6 votes vote down vote up
@Directive({
  selector: 'button[auiDialogClose]',
  exportAs: 'auiDialogClose',
})
export class DialogCloseDirective implements OnInit {
  @Input('auiDialogClose')
  result: any;

  constructor(
    @Optional() public dialogRef: DialogRef<any>,
    private readonly elementRef: ElementRef,
    private readonly dialogService: DialogService,
  ) {}

  ngOnInit() {
    if (!this.dialogRef) {
      this.dialogRef = getClosestDialog(
        this.elementRef,
        this.dialogService.openDialogs,
      );
    }
  }

  @HostListener('click')
  closeDialog() {
    this.dialogRef.close(this.result);
  }
}
Example #8
Source File: for-roles.directive.ts    From budget-angular with GNU General Public License v3.0 6 votes vote down vote up
@Directive({
  selector: "[forRoles]",
})
export class ForRolesDirective {
  roles: string[];

  @Input()
  set forRoles(roles: string[] | string) {
    if (roles != null) {
      this.roles = Array.isArray(roles) ? roles : [roles];
      this.roles = this.roles.map((r) => r.toUpperCase());
    } else {
      this.roles = [];
    }

    this.authService.getUserRole$().subscribe((role) => {
      if (role && !this.roles.includes(role.toUpperCase())) {
        this.viewContainer.clear();
      } else {
        this.viewContainer.createEmbeddedView(this.templateRef);
      }
    });
  }

  constructor(
    private viewContainer: ViewContainerRef,
    private templateRef: TemplateRef<any>,
    private authService: AuthService
  ) {}
}
Example #9
Source File: helper-directives.ts    From alauda-ui with MIT License 6 votes vote down vote up
@Directive({
  selector: '[auiCardHeader]',
  host: {
    '[class.aui-card__header]': 'true',
    '[class.aui-card__header--secondary]': 'size === "secondary"',
  },
})
export class CardHeaderDirective {
  @Input()
  size: 'default' | 'secondary' = 'default';
}
Example #10
Source File: password-validation.directive.ts    From blockcore-hub with MIT License 6 votes vote down vote up
@Directive({
    selector: '[appPasswordValidation]'
})
export class PasswordValidationDirective {
    constructor() { }

    static MatchPassword(AC: AbstractControl) {
        if (AC == null) {
            return;
        }

        const password = AC.get('accountPassword').value;
        const confirmPassword = AC.get('accountPasswordConfirmation').value;

        if (confirmPassword !== password) {
            AC.get('accountPasswordConfirmation').setErrors({ accountPasswordConfirmation: true });
        } else {
            AC.get('accountPasswordConfirmation').setErrors(null);
            return null;
        }
    }
}
Example #11
Source File: state-listener.component.ts    From angular-component-library with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Directive()
export class StateListener implements OnInit, OnDestroy {
    drawerOpenListener: Subscription;

    constructor(protected drawerService: DrawerService, protected changeDetector: ChangeDetectorRef) {}

    public ngOnInit(): void {
        this.listenForDrawerChanges();
    }

    public ngOnDestroy(): void {
        this.unsubscribeListeners();
    }

    public isOpen(): boolean {
        return this.drawerService.isDrawerOpen();
    }

    public isOpenOnHover(): boolean {
        return this.drawerService.isOpenOnHover();
    }

    public unsubscribeListeners(): void {
        if (this.drawerOpenListener) {
            this.drawerOpenListener.unsubscribe();
        }
    }

    listenForDrawerChanges(): void {
        this.drawerOpenListener = this.drawerService.drawerOpenChanges().subscribe(() => {
            this.changeDetector.detectChanges();
        });
    }
}
Example #12
Source File: hover.directive.ts    From ReCapProject-Frontend with MIT License 6 votes vote down vote up
@Directive({
  selector: '[appHover]',
})
export class HoverDirective {
  @Input() appHoverScale: number = 1.1;

  constructor(private elementRef: ElementRef) {}

  ngOnInit() {
    this.hover(1);
    this.elementRef.nativeElement.style.transition = 'transform 0.2s';
  }

  @HostListener('mouseenter') onMouseEnter() {
    this.hover(this.appHoverScale);
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.hover(1);
  }

  hover(scale: Number) {
    this.elementRef.nativeElement.style.transform = `scale(${scale})`;
  }
}
Example #13
Source File: display-activity-date-difference.directive.ts    From careydevelopmentcrm with MIT License 6 votes vote down vote up
@Directive({
  selector: '[displayActivityDateDifference]'
})
export class DisplayActivityDateDifferenceDirective extends SingleClassBaseDirective implements OnInit {

  @Input('displayActivityDateDifference') currentDateDifference: number;
  @Input('activity') activity: Activity;

  constructor() {
    super();
  }

  ngOnInit() {
    if (this.currentDateDifference) {
      this.setClass();
    }
  }

  private setClass() {
    let className: string = '';

    if (this.currentDateDifference > 0 && this.currentDateDifference < 36000) className = 'info-text';

    if (this.activity.type) {
      if (this.currentDateDifference < 0 && this.activity.type.usesStatus) className = 'error-text';
      if (this.currentDateDifference < 0 && !this.activity.type.usesStatus) className = 'warning-text';
    }

    this._elementClass = className;
  }
}
Example #14
Source File: widget.directive.ts    From json-schema-form with Apache License 2.0 6 votes vote down vote up
/**
 * directive for dynamically loading custom widgets
 */
@Directive({
    selector: '[libWidgetHost]'
})
export class WidgetDirective {

    /**
     * allow caller to dynamically insert custom component
     * @param viewContainerRef  dynamic component handle
     */
    constructor(public viewContainerRef: ViewContainerRef) { }
}
Example #15
Source File: external-link.directive.ts    From WowUp with GNU General Public License v3.0 6 votes vote down vote up
@Directive({
  selector: "[appExternalLink]",
})
export class ExternalLinkDirective {
  @HostListener("click", ["$event"]) public onClick($event: MouseEvent): void {
    $event.preventDefault();
    $event.stopPropagation();

    const target = ($event as any).path?.find((t) => t.tagName === "A");

    this._linkService.confirmLinkNavigation(target.href as string).subscribe();
  }

  public constructor(private _linkService: LinkService) {}
}
Example #16
Source File: closable.directive.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
@Directive({
  selector: "[isClosable]",
})
export class ClosableDirective {
  parent: DxcHeaderComponent;

  @HostListener("click") click() {
    this.parent.showMenu();
  }

  constructor(
    public elementRef: ElementRef,
    public viewContainerRef: ViewContainerRef,
    @Optional() parent: DxcHeaderComponent
  ) {
    if (parent) {
      this.parent = parent;
    }
  }
}
Example #17
Source File: read-time.directive.ts    From Angular-Cookbook with MIT License 6 votes vote down vote up
@Directive({
  selector: '[appReadTime]',
})
export class ReadTimeDirective implements OnInit {
  @Input() configuration: ReadTimeConfig = {
    wordsPerMinute: 200,
  };
  @Output() readTimeCalculated = new EventEmitter<string>();
  constructor(private el: ElementRef) {}

  ngOnInit() {
    const text = this.el.nativeElement.textContent;
    const time = this.calculateReadTime(text);
    const timeStr = this.createTimeString(time);
    console.log(timeStr);
    this.readTimeCalculated.emit(timeStr);
  }

  calculateReadTime(text: string) {
    const wordsCount = text.split(/\s+/g).length;
    const minutes = wordsCount / this.configuration.wordsPerMinute;
    return Math.ceil(minutes);
  }

  createTimeString(timeInMinutes) {
    if (timeInMinutes === 1) {
      return '1 minute';
    } else if (timeInMinutes < 1) {
      return '< 1 minute';
    } else {
      return `${timeInMinutes} minutes`;
    }
  }
}
Example #18
Source File: githubvaliddirective.ts    From barista with Apache License 2.0 6 votes vote down vote up
@Directive({
  selector: '[appgithubValidator]',
})
export class githubValidDirective {
  constructor(private gitHubUrlModel: NgModel, private projectApiService: ProjectApiService) {
    this.gitHubUrlModel.control.valueChanges.subscribe((value: string) => {
      if (value === undefined || value.length === 0) {
        return;
      }
      this.projectApiService.githubUrlValid(value).subscribe(
        (response) => {
          if (response === 'error') {
            this.gitHubUrlModel.control.setErrors({ gitHubUrlDoesNotExist: true });
          } else {
            return null;
          }
        },
        (error) => {},
      );
    });
  }
}
Example #19
Source File: header-outlet.directive.ts    From halstack-angular with Apache License 2.0 6 votes vote down vote up
/**
 * Provides a handle for the table to grab the view container's ng-container to insert data rows.
 * @docs-private
 */
@Directive({ selector: "[headerOutlet]" })
export class HeaderOutlet implements RowOutlet {
  constructor(
    public viewContainer: ViewContainerRef,
    public elementRef: ElementRef
  ) {}
}
Example #20
Source File: taskbar-item.directive.ts    From nica-os with MIT License 6 votes vote down vote up
@Directive({
  selector: '[appTaskbarItem]'
})
export class TaskbarItemDirective implements OnInit {
  itemAnimation: TimelineMax;
  constructor(
    public viewContainerRef: ViewContainerRef
  ) { }

  ngOnInit() {
    this.animateIn();
  }

  animateIn() {
    window.requestAnimationFrame(() => {
      this.itemAnimation = new TimelineMax({paused: true, reversed: false});
      this.itemAnimation.to(this.viewContainerRef.element.nativeElement, 1, {opacity: 1, ease: 'Expo.easeInOut'}, 0);
      this.itemAnimation.play();
    });
  }
}
Example #21
Source File: popper.directive.ts    From TypeFast with MIT License 6 votes vote down vote up
@Directive({
  selector: '[popper]',
})
export class PopperDirective {
  private popper: Instance;

  @Input() text: string;

  constructor(private readonly el: ElementRef) {}

  ngOnInit(): void {
    let tooltipEl = this.el.nativeElement.getElementsByClassName(
      'tooltip'
    )[0] as HTMLElement;

    if (this.text) {
      tooltipEl = document.createElement('div');
      tooltipEl.className = 'tooltip';
      tooltipEl.innerText = this.text;
      document.body.appendChild(tooltipEl);
    }
    this.popper = createPopper(this.el.nativeElement, tooltipEl, {
      placement: 'right' as Placement,
    });
  }

  ngOnDestroy(): void {
    if (!this.popper) {
      return;
    }

    this.popper.destroy();
  }
}
Example #22
Source File: clipboard.directive.ts    From xBull-Wallet with GNU Affero General Public License v3.0 6 votes vote down vote up
@Directive({
  selector: '[appClipboard]'
})
export class ClipboardDirective {
  @Input() textToCopy?: string | null;
  @Output() copied: EventEmitter<string> = new EventEmitter<string>();

  constructor(
    private readonly nzMessageService: NzMessageService,
    private readonly clipboardService: ClipboardService,
    private readonly translateService: TranslateService,
  ) {}

  @HostListener('click')
  copyToClipboard(): void {
    if (!this.textToCopy) {
      return;
    }

    try {
      this.clipboardService.copyToClipboard(this.textToCopy);
      this.copied.emit(this.textToCopy);

      this.nzMessageService.success(this.translateService.instant('SUCCESS_MESSAGE.COPIED_TO_CLIPBOARD'));
    } catch (e: any) {
      this.nzMessageService.error(this.translateService.instant('ERROR_MESSAGES.UNEXPECTED_ERROR'));
    }
  }

}
Example #23
Source File: banner.directive.ts    From rubic-app with GNU General Public License v3.0 6 votes vote down vote up
@Directive({
  selector: '[appBanner]'
})
export class BannerDirective {
  @Input() set appBanner(value: string) {
    if (value) {
      this.renderer.setStyle(this.elementRef.nativeElement, 'background', value);
    }
  }

  @Input() set color(value: string) {
    if (value) {
      this.renderer.setStyle(this.elementRef.nativeElement, 'color', value);
    }
  }

  constructor(private elementRef: ElementRef, private renderer: Renderer2) {
    renderer.addClass(elementRef.nativeElement, 'banner');
  }
}
Example #24
Source File: NgxMatHighlightDirective.ts    From angular-material-components with MIT License 6 votes vote down vote up
@Directive({
    selector: 'code[ngxMatHighlight]'
})
export class NgxMatHighlightDirective implements AfterViewInit {
    constructor(private eltRef: ElementRef) {
    }
    ngAfterViewInit() {
        hljs.highlightBlock(this.eltRef.nativeElement);
    }
}
Example #25
Source File: flex.directive.ts    From ng-devui-admin with MIT License 6 votes vote down vote up
@Directive({
  selector: `[daFlex], [daFlexMs], [daFlexMm], [daFlexMl], [daFlexXs], [daFlexSm], [daFlexMd], [daFlexLg], [daFlexXl]`,
})

export class DaFlexDirective implements OnInit, OnDestroy {
  private destroy$ = new Subject();

  @Input() daFlex: number | string;
  @Input() daFlexMs: number | string;
  @Input() daFlexMn: number | string;
  @Input() daFlexMl: number | string;
  @Input() daFlexXs: number | string;
  @Input() daFlexSm: number | string;
  @Input() daFlexMd: number | string;
  @Input() daFlexLg: number | string;
  @Input() daFlexXl: number | string;

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

  ngOnInit(): void {
    this.screenQueryService.getPoint()
    .pipe(takeUntil(this.destroy$))
    .subscribe(( {currentPoint }) => {
      setScreenPointFlex(currentPoint, this, this.elementRef, this.renderer);
    });
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
Example #26
Source File: dom.changed.directive.ts    From dbm with Apache License 2.0 6 votes vote down vote up
@Directive({
  selector: '[watchDom]'
})
export class DomChangedDirective implements OnInit {
  constructor(private elRef: ElementRef) {
  }

  ngOnInit() {
    this.registerDomChangedEvent(this.elRef.nativeElement);
  }

  registerDomChangedEvent(el) {
    const observer = new MutationObserver(list => {
      const evt =
        new CustomEvent('dom-changed', {detail: list, bubbles: true});
      el.dispatchEvent(evt);
    });
    const attributes = true;
    const childList = true;
    const subtree = true;
    observer.observe(el, {attributes, childList, subtree});
  }
}
Example #27
Source File: checkbox.directive.ts    From Bridge with GNU General Public License v3.0 6 votes vote down vote up
@Directive({
  selector: '[appCheckbox]'
})
export class CheckboxDirective implements AfterViewInit {
  @Output() checked = new EventEmitter<boolean>()

  _isChecked = false

  constructor(private checkbox: ElementRef) { }

  ngAfterViewInit() {
    $(this.checkbox.nativeElement).checkbox({
      onChecked: () => {
        this.checked.emit(true)
        this._isChecked = true
      },
      onUnchecked: () => {
        this.checked.emit(false)
        this._isChecked = false
      }
    })
  }

  check(isChecked: boolean) {
    this._isChecked = isChecked
    if (isChecked) {
      $(this.checkbox.nativeElement).checkbox('check')
    } else {
      $(this.checkbox.nativeElement).checkbox('uncheck')
    }
  }

  get isChecked() {
    return this._isChecked
  }
}
Example #28
Source File: numeric-color-input.directive.ts    From angular-material-components with MIT License 6 votes vote down vote up
@Directive({
  selector: '[ngxMatNumericColorInput]'
})
export class NumericColorInputDirective {

  constructor() { }

  @HostListener('input', ['$event'])
  onInput($event: any) {
    this._formatInput($event.target);
  }

  /**
* Format input
* @param input 
*/
  private _formatInput(input: any) {
    let val = Number(input.value.replace(NUMERIC_REGEX, ''));
    val = isNaN(val) ? 0 : val;
    input.value = val;
  }

}
Example #29
Source File: base-component.directive.ts    From golden-layout-ng-app with MIT License 6 votes vote down vote up
@Directive()
export abstract class BaseComponentDirective {
    constructor(public rootHtmlElement: HTMLElement) {

    }

    setPositionAndSize(left: number, top: number, width: number, height: number) {
        this.rootHtmlElement.style.left = this.numberToPixels(left);
        this.rootHtmlElement.style.top = this.numberToPixels(top);
        this.rootHtmlElement.style.width = this.numberToPixels(width);
        this.rootHtmlElement.style.height = this.numberToPixels(height);
    } 

    setVisibility(visible: boolean) {
        if (visible) {
            this.rootHtmlElement.style.display = '';
        } else {
            this.rootHtmlElement.style.display = 'none';
        }
    }

    setZIndex(value: string) {
        this.rootHtmlElement.style.zIndex = value;
    }

    private numberToPixels(value: number): string {
        return value.toString(10) + 'px';
    }
}