有没有办法将指令(ngx-mask
在我的例子中)添加到具有命名HTML 元素的现有 Angular 组件input
(#datePicker
在下面的示例中)?
示例设置
假设我有一个名为InputDate.component.ts
如下所示的组件。组件中的模板(HTML 部分)调用另一个选择器为bb-input-datepicker-ui
. 该选择器的组件 -InputDatepicker.component.ts
在其模板元素中包含label
和input
,但假设我们没有立即可用的源代码 - 我们只能通过@Input()
字段将值传递给它。
@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);
}
}
愿望
我希望能够将ngx-mask
指令锁定在InputDatepicker
'input
元素上。现在,如果我在最后重新创建InputDatepicker
组件,我需要做的就是添加一个像这样的掩码key=value对作为以下属性之一input
:
<input ... mask="00/00/0000" ...>
这将保证两件事:1)只能输入数字,2)日期自动格式化为显示的掩码 - 太好了。
也就是说,我想按InputDatepicker
原样使用组件,并且不应该在理想情况下重新创建它。因此,问题是:我可以以某种方式动态添加掩码指令吗?
已经完成了...
如果您看到ngAfterViewInit()
上述内容,您应该会看到这样做的谦虚尝试。将console.log
打印类似于下面的输出的内容,并显示placeholder
正在添加的属性,并且 UI 确实显示了它。然而,该指令没有运气mask
,即使它显示在输出中。我想这不是input
动态锁定元素指令的正确方法。
<input type="text" class="form-control" ... placeholder="77/99/5555" mask="00/00/0000">
感谢您的时间朋友。