コンポーネントのEventEmitter
は、場合によっては起動しますが、それ以外の場合は起動しません。どうして?Angular2:EventEmitterが起動することがあります。
私はカスタムの日付ピッカーを持っています。日付を手動で変更する(<input>
)か、ng2-bootstrap <datepicker>
を使用して便利に選択することができます。
私は、このテンプレートを持っている:
<input [(ngModel)]="dateString"
class="form-control"
(focus)="showPopup()"
(change)="inputChange()">
<datepicker class="popup" [ngClass]="{ 'popup-hidden': !showDatepicker }"
[(ngModel)]="dateModel"
[showWeeks]="true"
(ngModelChange)="hidePopup($event)">
</datepicker>
関連部品と部品:
export class CustomDatepickerComponent {
@Input()
dateModel: Date;
dateString: string;
showDatepicker = false;
@Output()
dateModelChange: EventEmitter<Date> = new EventEmitter();
showPopup() {
this.showDatepicker = true;
}
// Called when the date is changed manually
// It DOES fire the event
inputChange() {
let result = moment(this.dateString, 'YYYY-MM-DD');
this.update(result.toDate());
}
// Called through the DatePicker of ng-bootstrap
// It DOESN'T fire the event
// However, the showDatepicker binding takes effect (see template)
hidePopup(event: Date) {
showDatepicker = false;
this.update(event);
}
update(date: Date) {
this.dateModel = date;
this.dateString = moment(date).format('YYYY-MM-DD');
// This SHOULD fire the event
// It is called in BOTH cases!
// But it fires only when the date is changed through the <input>
this.dateModelChange.emit(this.dateModel);
}
私はこの日付ピッカーをこのように使用します。
<custom-datepicker [dateModel]="testDate" (change)="change($event)"></custom-datepicker>
ここchange()
ハンドラ関数です。
testDate = new Date();
change($event) { console.info('CHANGE', $event); }
何をのsetTimeoutとそれを包みますか?同様に: 'setTimeout(()=> {this.dateModelChange.emit(this.dateModel);}、0);' – echonax
動作しません。上のコードに 'showDatepicker'メンバを追加しました。エミッタが起動していないときでも、バインディングを通してその変更が有効になるということは面白いです。 –