组件不向父组件发回值

时间:2016-05-06 16:09:47

标签: angular eventemitter

我的某个组件出了问题,问题是它在模型更改时似乎没有发出模型。它适用于我的其他组件,但是不管我做了什么,它都不起作用。

选择组件:

import {Component, Input, Output, EventEmitter, OnInit, DoCheck} from 'angular2/core';

@Component({
  selector: 'form-select',
  templateUrl: './app/assets/scripts/modules/form-controls/form-select/form-select.component.html',
  styleUrls: ['./app/assets/scripts/modules/form-controls/form-select/form-select.component.css'],
  inputs: [
    'options',
    'callback',
    'model',
    'modelProperty',
    'optionProperty',
    'disabled',
    'allowEmpty',
    'label'
  ]
})

export class FormSelectComponent implements OnInit, DoCheck {
  @Input() model: any;
  @Output() onModelChange: EventEmitter<any> = new EventEmitter();

  private isOpen: boolean = false;
  private previousModel: any = null;

  ngOnInit() {

    // If no model is set and the select shouldn't be allowed empty, set the model to the first option
    if (!this.model && !this.allowEmpty) {
      this.model = this.options[0];
    }
    // If it should be allowed empty, set it to null which will add an empty class in the markup
    else if (this.allowEmpty) {
      this.model = null;
    }
  }

  ngDoCheck() {

    // Check if the model changes and emit it if it does
    if (this.previousModel !== this.model) {
      this.onModelChange.emit(this.model);
    }

    this.previousModel = this.model;
  }

  toggle() {

    if (this.disabled) {
      this.isOpen = false;

      return false;
    }

    this.isOpen = !this.isOpen;
  }

  close() {
    this.isOpen = false;
  }

  select(option) {
    this.model = option;
    this.close();

    this.callback ? this.callback() : false;
  }

  isSelected(option) {
    return option[this.modelProperty] === this.model[this.modelProperty];
  }
}

当我使用pre检查值时,尽管模型在组件内部发生了变化,但值保持不变:

<div class="col-xs-12 m-b-xxs">
  <pre>{{user.country}}</pre>
  <form-select [(model)]="user.country" modelProperty="country" [options]="countries" optionProperty="country" label="Country"></form-select>
</div>

我做错了什么?

1 个答案:

答案 0 :(得分:1)

有一个多余的on

@Output() onModelChange: EventEmitter<any> = new EventEmitter();

应该是

@Output() modelChange: EventEmitter<any> = new EventEmitter();

对于速记双向绑定语法[(...)],除了输出的Change后缀之外,属性(输入和输出)的名称必须相同。