angular2从指令访问ngModel变量 [英] angular2 access ngModel variable from a directive
问题描述
我正在尝试构建如下所示的日期时间选择器指令。
< input [(ngModel)] = date1 datetime-picker date-only />
I am trying to build a datetime picker directive like the following.
<input [(ngModel)]="date1" datetime-picker date-only />
和 date1
被指定为日期,例如 new Date()
and date1
is assigned as a Date, e.g., new Date()
当我将其显示为html时,输入元素中的文本如下所示
2015年1月1日星期四00:00:00 GMT-0500
When I display this in html, text in input element looks like the following
Thu Jan 01 2015 00:00:00 GMT-0500
我想显示如下内容
2015-01-01 00:00:00
我想在指令中格式化日期
I want to format date WITHIN a directive using DatePipe instead of showing result from default toString() function.
我的问题是;使用DatePipe而不是显示默认toString()函数的结果。 在指令内,如何访问ngModel变量?,例如date1,以便可以添加toString()方法。
My question is; "within a directive, how do I access ngModel variable?", e.g., date1, so that I can add toString() method.
如果我的方法不合适,
If my approach is not right, please advise me.
推荐答案
这是侦听和通知ngModel的简单方法。我刚刚使用jQuery进行了演示,以方便理解。实际上,它可以是任何东西。
Here is simple and easy way to listen and notify ngModel. I have just demonstrated with jQuery for easy understanding. Practically, it can be anything.
import { Directive, ElementRef } from '@angular/core';
import { NgModel } from '@angular/forms';
@Directive({
selector: `[ngModel][customDir]`,
providers: [NgModel]
})
export class CustomDirective {
constructor(private element: ElementRef, private ngModel: NgModel) {
}
ngOnInit() {
let that = this;
/* Here you can write custom initialization code */
/* Listening to the value of ngModel */
that.ngModel.valueChanges.subscribe(function (value) {
/* Set any value of your custom control */
$(that.element.nativeElement).data("newValue",value);
});
/* Inform ng model for any new change happened */
$(that.element.nativeElement).bind("customEvent",function (someNewValue) {
that.ngModel.update.emit(someNewValue);
}
});
}
}
这篇关于angular2从指令访问ngModel变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!