7

这是子组件:

@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 函数并且不会出错,该事件永远不会到达父组件。有任何想法吗?

4

1 回答 1

3

您必须将您的父组件绑定到您的子组件,将您的父 html 更改为:

 <header>
    <kg-dateSpinner (onChanged)="onChanged($event)" (onLoadFood)="onLoadFood($event)"></kg-dateSpinner> 
 </header>

所以括号里面是你的子输出名称,引号里面是你的父函数

于 2016-10-13T14:25:51.293 回答