无法以角度反应形式填充下拉列表

时间:2019-12-05 00:19:47

标签: angular angular-material angular-reactive-forms

使用模板驱动的表单时,我能够填充下拉列表,但是现在我不能以物质反应形式填充下拉列表。我正在尝试填充country下拉列表,以便以后可以调用onstatechange事件来根据所选国家/地区填充states。这是我的代码

    <div fxLayout="row wrap" class="pt-4">
        <mat-form-field appearance="outline" fxFlex="33">
            <mat-label>Select a Country</mat-label>
            <mat-select [compareWith]="compareThese" formControlName="countryCtrl" (selectionChange)="loadState($event)">
                <mat-option *ngFor="let item of countriesData$ | async" [value]="item.id">
                    {{ item.name }}
                </mat-option>
            </mat-select>
            <mat-icon matSuffix class="disabled-text">account_circle</mat-icon>
        </mat-form-field>
        <mat-form-field appearance="outline" fxFlex="34" class="px-8">
            <mat-label>Select a State</mat-label>
            <mat-select [compareWith]="compareThese" formControlName="stateCtrl" (selectionChange)="loadCity($event)">
                <mat-option *ngFor="let item of filteredStates$ | async" [value]="item.id">
                    {{ item.name }}
                </mat-option>
            </mat-select>
            <mat-icon matSuffix class="disabled-text">account_circle</mat-icon>
        </mat-form-field>
        <mat-form-field appearance="outline" fxFlex="33">
            <mat-label>Select a City</mat-label>
            <mat-select [compareWith]="compareThese" formControlName="cityCtrl">
                <mat-option *ngFor="let ele of filteredCities$ | async" [value]="ele.id">
                    {{ ele.name }}
                </mat-option>
            </mat-select>
            <mat-icon matSuffix class="disabled-text">account_circle</mat-icon>
        </mat-form-field>
    </div>

这是我的JSON的样子

enter image description here

ts文件代码

export class ManualFormComponent implements OnInit {

  countryCtrl: any;
  stateCtrl: any = {};
  cityCtrl: any = {};
  manualOrderForm: FormGroup;
  zoom: any;

  countriesData$: Observable<ICountry[]>;
  filteredStates$: Observable<IState[]>;
  filteredCities$: Observable<ICity[]>;

  constructor(
    private _cityStateService: CountryStateCityService,
    private _fb: FormBuilder) {
    this.manualOrderForm = this._fb.group({
      countryCtrl: [[], Validators.required], 
      stateCtrl: [[], Validators.required],
      cityCtrl: [[], Validators.required],
    });
  }

  submit() {
    console.log(this.manualOrderForm);
  }

  compareThese(o1: any, o2: any) {
    return o1 === o2 ? true : false;
  }

  ngOnInit() {
    this._cityStateService.getCountriesStatesCity().subscribe(val => {
      console.log(val);
      this.countriesData$ = val[0];
      console.log(this.countriesData$);
    });
  }

}

国家/地区接口

import { IState } from './iState';

export interface ICountry {
  name: string;
  id: string;
  states: IState[];
}

状态

import { ICity } from './iCity';
export interface IState {
  cities: ICity[];
  id: string;
  name: string;
  countryId: string;
}

1 个答案:

答案 0 :(得分:1)

以反应形式使用mat-select时,您需要FormControl来存储form中的值,并需要单独的类变量来存储值的选项数组。

组件

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  form: FormGroup;

  dropdownval = [ ]; // variable to store array (options)

  constructor(private dataService: DataService, private formBuilder: FormBuilder) {
    this.form = this.formBuilder.group({
      dropdown: ['', Validators.required] // form control which will hold form selected value
    });
  }

  onEvent() {
    this.dataService.getData().subscribe(res => {
      console.log(res);
      this.dropdownval = res;
    })
  }
}

模板

<form [formGroup]="form">

    <mat-form-field>
        <mat-label>Select a Country</mat-label>
    <!-- dropdown is used for formcontrol value -->
        <mat-select [formControl]="dropdown">
      <!-- dropdownval holds values for options -->
            <mat-option *ngFor="let item of dropdownval"> 
                {{ item.name }}
            </mat-option>
        </mat-select>
    </mat-form-field>

</form>

我已经Stackblitz了。我考虑了从服务中获取数据的情况。因此,首先单击获取数据,然后您将看到填充下拉列表。