使用反应形式从一项服务中读取数据并创建列表

时间:2018-12-18 13:25:20

标签: angular angular-services angular-reactive-forms ngfor

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

product.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>

2 个答案:

答案 0 :(得分:0)

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

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>

答案 1 :(得分:0)

在组件中创建一个get变量,然后调用服务pdcSols

export class HomeComponent {
  get pdcSols(): { cod: string; denumire: string }[] {
      return this.pdc.pdcSol;
  }
}

并在模板中调用它

  <option *ngFor="let pdcSol of pdcSols" [value]="pdcSol.cod">{{ pdcSol.denumire }}</option>