gpt4 book ai didi

angular - 无法使用具有选择值的 patchValue 绑定(bind)到对象

转载 作者:行者123 更新时间:2023-12-05 07:24:31 33 4
gpt4 key购买 nike

我正在使用 Angular 表单生成器添加数据,其中表单有一个选择元素,其值是绑定(bind)到对象,但是当我尝试使用补丁值方法或设置值方法字段编辑表单时,除了选择正在获取提交了正确的数据,请有人纠正我。

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>

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]]
});
}

}

{{国家|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"}

最佳答案

我想出了一个适合我的解决方案,问题是什么:我正在尝试为在 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';
}

关于angular - 无法使用具有选择值的 patchValue 绑定(bind)到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55377837/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com