这是子组件:
@Component({
selector: 'kg-dateSpinner',
templateUrl: 'kgDateSpinner.component.html',
styleUrls: ['kgDateSpinner.component.css']
})
export class KgDateSpinnerComponent implements OnInit {
@Output() onChanged = new EventEmitter<DateSpinnerReturn>();
@Output() onLoadFood = new EventEmitter<DateSpinnerReturn>();
sr: DateSpinnerReturn;
userSettings: User;
cd = moment();
currentDate: string = this.cd.format("MMMM DD, YYYY");;
dateSpinnerForm: FormGroup;
constructor(
private ts: ThemeService,
private fb: FormBuilder,
private ss: SettingsService) {
this.sr = new DateSpinnerReturn();
}
ngOnInit() {
this.dateSpinnerForm = this.fb.group({
currentDate: [this.currentDate, []]
});
}
onLoadFoodRequest() {
this.sr.spinValue = this.currentDate;
this.onLoadFood.emit(this.sr)
}
onDateSelected(event: any) {
this.cd = moment(event);
this.returnEvent();
}
onIncrement() {
this.cd = this.cd.add(1, 'day');
this.returnEvent();
}
onDecrement() {
this.cd = this.cd.subtract(1, 'day');
this.returnEvent();
}
returnEvent() {
this.currentDate = this.cd.format("MMMM DD, YYYY");
this.dateSpinnerForm.controls['currentDate'].setValue(this.currentDate, { onlySelf: true });
this.sr.spinValue = this.currentDate;
this.onChanged.emit(this.sr)
}
子组件html:
<form [formGroup]="dateSpinnerForm" class="ui form" novalidate>
<button pButton (click)="onDecrement()" icon="fa-backward"></button>
<div style="padding-top: 10px;width: 208px; display: inline-block;">
<p-calendar formControlName="currentDate" showAnim="slideDown" (onSelect)="onDateSelected($event)" [showIcon]="true" [readonlyInput]="true" dateFormat="MM d, yy"></p-calendar>
</div>
<button pButton (click)="onIncrement()" icon="fa-forward"></button>
<button pButton (click)="onLoadFoodRequest()" icon="fa-cutlery" iconPos="left"></button>
</form>
父组件:
onChanged(sr: DateSpinnerReturn) {
this.diaryDate = sr.spinValue;
}
onLoadFood(sr: DateSpinnerReturn) {
this.diaryDate = sr.spinValue;
}
父html:
<header>
<kg-dateSpinner></kg-dateSpinner>
</header>
onChanged事件接收来自孩子的数据,但是onLoadFood没有。 按子组件上的按钮激活LoadFoodRequest函数并且不会发生错误,该事件永远不会使其成为父级。有什么想法吗?
答案 0 :(得分:2)
您必须将父级绑定到子组件,将父级html更改为:
<header>
<kg-dateSpinner (onChanged)="onChanged($event)" (onLoadFood)="onLoadFood($event)"></kg-dateSpinner>
</header>
因此括号内是您的子输出名称,引号内是您的父函数