选择值绑定到对象

时间:2019-03-27 12:59:49

标签: angular angular-forms

我正在使用角度表单生成器来添加数据,其中表单具有其值是绑定到对象的select元素,但是当我尝试使用补丁值方法或设置值方法字段来编辑表单时,除了select之外,提交了正确的数据,请有人纠正我。

html

  <form [formGroup]="addCountryForm">
    <div class="form-group">
      <label for="countryControl">Name</label>
      <select class="form-control" formControlName="countryControl" (change)="resetwarning()">        
        <option [ngValue]="country" *ngFor="let country of countries">
          {{country.name}}
        </option>
      </select>          
    </div>
    <div class="form-group">
      <label for="note">Note</label>
      <textarea rows="4" class="form-control" placeholder="Enter any Note (If Any)" formControlName="note"></textarea>          
    </div>
  </form>

ts

export class AddCountryComponent implements OnInit {

  addCountryForm: FormGroup;

  data: any;
  heading: string;
  countries = [];
  customeError: boolean;
  customeErrorMsg: string;

  constructor(
    public activeModal: NgbActiveModal,
    private fb: FormBuilder,
    private countryService: CountriesService
  ) { }

  ngOnInit() {
    this.countries = this.countryService.allCountryList();
    this.createForms();
    if (this.data) {
      console.log(this.data.details);
      this.addCountryForm.setValue({
        countryControl: this.data.details,
        note: this.data.note
      }
      );
      this.heading = 'Edit Country';
    } else {
      this.heading = 'Add Country';
    }
  }

  createForms() {
    this.addCountryForm = this.fb.group({
      countryControl: [''],
      note: ['', [Validators.required]]
    });
  }   

}

{{countries | json}}

示例输出

[
  {
    "id": "1",
    "sortname": "AF",
    "name": "Afghanistan",
    "phonecode": "93"
  },
  {
    "id": "2",
    "sortname": "AL",
    "name": "Albania",
    "phonecode": "355"
  },
  {
    "id": "3",
    "sortname": "DZ",
    "name": "Algeria",
    "phonecode": "213"
  }
 ]

console.log(this.data.details);

输出

 {id: "1", sortname: "AF", name: "Afghanistan", phonecode: "93"}

1 个答案:

答案 0 :(得分:0)

我想出了一种对我有用的解决方案, 有什么问题: 我正在尝试为json对象数组中的值做一个下拉值的补丁值和设置值,因此它正在与对象进行比较以设置所选值,我做了以下操作:

ngOnInit() {
this.countries = this.countryService.allCountryList();
this.createForms();
if (this.data) {
  const selectedCountry = this.countries.find(item => JSON.stringify(item) === JSON.stringify(this.data.details));
  this.addCountryForm.patchValue({
    countryControl: selectedCountry,
    note: this.data.note
  }
  );
  this.heading = 'Edit Country';
} else {
  this.heading = 'Add Country';
}

}