表单下拉选择菜单值未定义 - Angular 2

时间:2017-02-17 19:10:35

标签: angular typescript

我正在尝试获取所选下拉列表的值,我尝试使用

console.log(this.myForm.controls['SignUpForm'].value['states'];

但它正在返回' undefined'。一些帮助将不胜感激。这是我的完整代码。

index.component.html

<form novalidate [formGroup]="myForm" (ngSubmit)="onSignUp()" autocomplete="off">
  <div formGroupName="SignUpForm">
    <div>
      <select formControlName="state" title="University">
        <option *ngFor="let state of states" [ngValue]="state">{{state.abbrev}}</option>
      </select>
    </div>
  </div>
  <div>
    <button type="submit" name="action">Sign Up</button>
  </div>
</form>

helloworld.component.ts

export class HelloWorldComponent implements OnInit {
  myForm: FormGroup;
  constructor(private _fb: FormBuilder){ }

  states = [
    {name: 'Arizona', abbrev: 'AZ'},
    {name: 'California', abbrev: 'CA'},
    {name: 'Colorado', abbrev: 'CO'},
    {name: 'New York', abbrev: 'NY'},
    {name: 'Pennsylvania', abbrev: 'PA'},
  ];

  onSignUp(): void {
    console.log(this.myForm.controls['SignUpForm'].value['abbrev'])
  }

  ngOnInit() {
    this.myForm = this._fb.group({
      SignUpForm: this._fb.group({
        state: [this.states, Validators.compose([
          Validators.required
        ])]
      })
    });
    $(document).ready(function() {
      $('select').material_select();
    });
  }
}

1 个答案:

答案 0 :(得分:0)

你可以用两种方式做到这一点。如果你想通过myForm.value,那么:

(ngSubmit)="onSignUp(myForm.value)" 

您可以从中提取值:

onSignUp(formValues): void {
  console.log(formValues.SignUpForm['state'])
}

如果您不想这样做,可以通过以下方式获取值:

console.log(this.myForm.get('SignUpForm').get('state').value)

示例Plunker