Is there a way to add a directive - ngx-mask
in my case - to an existing Angular component that has a named HTML element input
(#datePicker
in the example below)?
Example setup
Suppose I have a component called InputDate.component.ts
as shown below. The template in the component - the HTML part - calls another component whose selector is bb-input-datepicker-ui
. This selector's component - InputDatepicker.component.ts
- has within its template elements such as label
and input
, but it's assumed that we do not have its sourcecode immediately available - we can only pass values to it through the @Input()
fields.
@Component({
selector: 'bb-us-formly-input-date',
template: `<bb-input-datepicker-ui
[label]="to.label"
[formControl]="formControl"
[minDate]="to.minDate"
#datePicker
></bb-input-datepicker-ui>
`,
})
export class InputDateComponent extends FieldType implements AfterViewInit {
@ViewChild('datePicker', { static: true })
datePickerComponent: any;
ngAfterViewInit() {
// sample experiment code
let comp:HTMLElement = this.datePickerComponent.datePickerInput.nativeElement;
comp.setAttribute('placeholder', '77/99/5555')
comp.setAttribute('mask', '00/00/0000')
console.log('==', comp);
}
}
Wishes
I would like to be able to latch the ngx-mask
directive on the InputDatepicker
's input
element. Now, if I re-create the InputDatepicker
component at my end, all I would need to do is add a mask key=value pair like this as one of the many attributes of input
:
<input ... mask="00/00/0000" ...>
which would guarantee two things: 1) only digits can be typed in, and 2) date is auto-formatted to the mask shown - wonderful.
That said, I would like to use InputDatepicker
component as-is and should not ideally re-create it at my end. Hence the question: can I somehow add the mask directive dynamically to it?
Already done...
If you see the ngAfterViewInit()
above, you should see a humble attempt at doing this. The console.log
would print something like the output below, and would show the placeholder
attribute being added and the UI does show it. No luck with the mask
directive however, even though it's shown in the output. It's just not the right way of latching directives on input
elements dynamically I suppose.
<input type="text" class="form-control" ... placeholder="77/99/5555" mask="00/00/0000">
Thanks for your time friends.