无法获得打字稿角度8中的下拉值

时间:2019-12-05 16:12:59

标签: angular typescript angular8

我想从html中将下拉选项值放入我的app.component.ts文件中,我收到了所有输入值,但无法将下拉值放入打字稿文件中。

我的search.component.html文件:

 <form [formGroup]="registerForm" (ngSubmit)="registerYourself()">
    <select class="wide" id="countrycode" formControlName="countryCode">
        <option *ngFor="let code of countryCodes" [ngValue]="code.value">{{ code.title }}</option>
    </select>
    <select class="wide" id="box" formControlName="category">
        <option *ngFor="let cat of vendorType" [ngValue]="cat.value">{{ cat.title }}</option>
    </select>
    <button type="submit" class="btn btn-default">Signup</button>
</form>

我的search.component.ts文件:

import { Component, OnInit } from '@angular/core';
import { NgForm, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';


@Component({
  selector: 'app-vendor-form',
  templateUrl: './vendor-form.component.html',
  styleUrls: ['./vendor-form.component.css']
})


export class VendorFormComponent implements OnInit {
  vendorType:Array<any>;
  countryCodes:Array<any>;
  selectedCode :string = '';
  registerForm:FormGroup;

  constructor(private fb:FormBuilder) { 
    this.vendorType = [
      { value: 'Corporate', title: 'Corporate', label: 'Corporate' }, 
     { value: 'Partner', title: 'Partner', label: 'Partner' },
     { value: 'Company Nomination', title: 'Company Nomination', label: 'Company Nomination' }
   ];
   this.countryCodes = [
     { value: '+1', title: '+1', label: 'USA' }, 
     { value: '+91', title: '+91', label: 'India' }
   ];
  }

  ngOnInit(){


    this.registerForm = this.fb.group({
      countryCode :["", [Validators.required]],
      category : ["", [Validators.required]]
    });
  }
  registerYourself(){
    var user = this.registerForm.value;
    console.log(user);

  }


}

2 个答案:

答案 0 :(得分:2)

尝试此stackblitz。您希望在加载组件时已在表单中选择了初始值。为此,您必须在formControls中设置默认值。示例:

 this.registerForm = this.fb.group({
      countryCode :["+1", Validators.required],
      category : ["Corporate", Validators.required]
    });

答案 1 :(得分:1)

尝试一下:

<form [formGroup]="registerForm" (ngSubmit)="registerYourself()">
     <select class="wide" id="countrycode" [formControl]="registerForm.get('countryCode')">
         <option *ngFor="let code of countryCodes" [value]="code.value"> 
             {{code.title }}
         </option>
     </select>
     <select class="wide" id="box" [formControl]="registerForm.get('category')">
         <option *ngFor="let cat of vendorType" [value]="cat.value">
              {{ cat.title }}</option>
     </select>
     <button type="submit" class="btn btn-default">Signup</button>
</form>