简体   繁体   中英

How can I add a directive to all instances of Angular Material datepicker?

I have created a custom directive for checking manual entries in angular material date picker ( with help of here ), and it is working.

Q: Is there any way to add that directive to all instances that are already present in the project without adding the directive one by one?

My directive:

import { Directive, ElementRef, HostBinding, OnDestroy, OnInit } from '@angular/core';
import * as textMask from '../../../util/vanillaTextMask.js';

@Directive({
  selector: `fed-mask, [fed-mask], [fedMask]`
})
export class FedMaskDirective implements OnInit, OnDestroy {
  @HostBinding('class.fed-mask') compClass = true;


  fedMask = {
    mask: [
      new RegExp('\\d'),
      new RegExp('\\d'),
      '.',
      new RegExp('\\d'),
      new RegExp('\\d'),
      '.',
      new RegExp('\\d'),
      new RegExp('\\d'),
      new RegExp('\\d'),
      new RegExp('\\d')
    ],
    showMask: false,
    guide: false,
    placeholderChar: '_'
  };

  maskedInputController;

  constructor(private element: ElementRef) { }

  ngOnInit(): void {
    this.maskedInputController = textMask.maskInput({
      inputElement: this.element.nativeElement,
      ...this.fedMask
    });
  }

  ngOnDestroy() {
    this.maskedInputController.destroy();
  }
}

how I'm currently using it:

  <mat-form-field>
                <input
                  (dateChange)="DateChange($event)"
                  formControlName="Date"
                  [matDatepicker]="Datepicker"
                  matInput
                  placeholder="Date"
                  (click)="Datepicker.open()"
                  fedMask
                >
                <mat-datepicker-toggle matSuffix [for]="Datepicker"></mat-datepicker-toggle>
                <mat-datepicker #Datepicker></mat-datepicker>
                <mat-error *ngIf="form.get('Date').hasError('required')">
                  Error
                </mat-error>
              </mat-form-field>

Expectation:

is there any way to add the fedMask directive to every instance of material date picker input without manually adding it for every time it has been used in the whole project?

you can use any existing attribute as a selector, for example

@Directive({
  selector: "matDatepicker",
})

will target every element that has the attribute matDatepicker present on it.

Another example:

@Directive({selector: 'input:([matDatepicker])' })

will target every input with the matDatepicker attribute.

The same goes for tags:

@Directive({
  selector: "mat-datepicker",
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM