您好我正在将应用程序升级到angular 2.我正在创建一个新的datepicker组件,包装一个vanilla javascript datepicker(pikaday)该组件看起来很棒,但是当我选择一个日期时,我看不到我的角度模型中的那些变化。
constructor(myInput: ElementRef) {
let opts = {
field: myInput.nativeElement,
format: 'YYYY-MM-DD',
onSelect: () => {
this.value = this.datePicker.getMoment().format(this.dateFormat);
}
};
this.datePicker = new Pikaday(opts);
}
<!---- template --->
<div class="cad-date-picker field">
<label class="field__in el-w100">
<input class="input" value="{{value}}" readOnly/>
<div class="field__icon">
<cad-icon name="calendar"></cad-icon>
</div>
</label>
</div>
----------------------------------------
<!---- Page --->
<div class="field">
<label class="field__in el-w100">
<input class="input" name="startDate" cad-date-time-picker="vm.startDateOptions" ng-required="vm.isSubmitting" ng-model="vm.rfp.startDate" ng-model-options="{allowInvalid: false}" ng-change="vm.dateChange('startDate')"/>
<div class="field__icon">
<cad-icon name="calendar"></cad-icon>
</div>
</label>
</div>
<cad-date-picker [(value)]="vm.rfp.startDate"></cad-date-picker>
在使用这两个组件进行测试时,向上组件为角度1,向下组件为角度2。
我已经尝试过这样做post,但它不起作用
答案 0 :(得分:2)
你应该知道Angular中的双向绑定是由EventEmitter
完成的,以Toughtram的为参考
发表https://blog.thoughtram.io/angular/2016/10/13/two-way-data-binding-in-angular-2.html
@Component({
selector: 'my-date-picker',
template: `<div class="my-date-picker field">
<label class="field__in el-w100">
<input #myDateInput class="input" [(ngModel)]="value" readOnly/>
<div class="field__icon">
<my-icon name="calendar"></cad-icon>
</div>
</label>`,
styles: [require('./date-picker.scss')],
encapsulation: ViewEncapsulation.None
})
export class DatePickerComponent implements OnInit {
@ViewChild('myDateInput') myInput: ElementRef;
@Input() dateFormat = 'YYYY-MM-DD';
@Input() get value() {
return this._value;
}
@Output() valueChange = new EventEmitter();
set value(newVal: string) {
this._value = newVal;
this.valueChange.emit(this._value);
}
private datePicker: any;
private _value: string;
ngOnInit() {
let opts = {
field: this.myInput.nativeElement,
format: this.dateFormat,
onSelect: () => {
this.value =
this.datePicker.getMoment().format(this.dateFormat);
}
};
this.datePicker = new Pikaday(opts);
}
}
这样,你可以处理来自外部的价值......