首页 > 解决方案 > 使用响应式表单从一个服务中读取数据并创建一个列表

问题描述

我用一些带有名称和代码的产品创建了一项服务。我想使用该对象列表并创建一个列表。请帮我!:) 谢谢

产品.service.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DateService {
  get pdcSol(): { cod: string; denumire: string }[] {
return this._pdcSol;
}

constructor() { }    

private _pdcSol = [
{cod: '065095', denumire: 'Pompa de caldura sol apa F1145-8 '},
{cod: '065096', denumire: 'Pompa de caldura sol apa F1145-10 '},
{cod: '065097', denumire: 'Pompa de caldura sol apa F1145-12 '}];
}

home.component.ts

import { DateService } from '../date.service';

export class HomeComponent implements OnInit {

constructor(private pdc: DateService) {}
}

home.component.html

<form [formGroup]="formSol">
    <select formControlName="modelPDC">
      <option *ngFor="let pdcSol of this.pdc._pdcSol.denumire" 
       [value]="pdcSol">{{ pdcSol }}</option>
    </select>
</form>

标签: angularangular-servicesangular-reactive-formsngfor

解决方案


您可以将服务分配给组件公共属性。

import { DateService } from '../date.service';

export class HomeComponent implements OnInit {
formSol: FormGroup;
dropdownArr:any;
constructor(private pdc: DateService, private formBuilder: FormBuilder) {}

ngOnInit(){
 this.dropdownArr = this.pdc.pdcSol;
 this.formSol = this.formBuilder.group({
   modelPDC: ['']
 });
 this.formSol.controls['modelPDC'].valueChanges.subscribe(value => {console.log(value);});
}

}

模板:

<form [formGroup]="formSol">
    <select formControlName="modelPDC">
      <option *ngFor="let pdcSol of this.dropdownArr" 
       [value]="pdcSol.denumire">{{ pdcSol.denumire }}</option>
    </select>
</form>

推荐阅读