У меня есть образец формы, в который я отправляю данные и редактирую их, заполняя ту же запись в Форме, где я разработал форму с использованием FormGroup, и связываю значения с помощью методов API управления формой get (). Setvalue () для текстовые вводы, но я изо всех сил пытаюсь заполнить DropDowns (выбрать) при редактировании
Я использую эту строку для заполнения определенного раскрывающегося списка редактируемой записи, как показано ниже
this.form.controls [ 'p_county']. setValue (county [0] .county_id, {onlySelf: true});
<form [formGroup]="form">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="form-label">Country</label>
<select class="form-control" formControlName="p_country">
<option *ngFor="let element of country" [value]="element.country_id">{{element.country_name}}</option>
</select>
<span class="text-danger" *ngIf="f.p_country.touched && f.p_country.errors?.required">Please Select Country</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label">State</label>
<select formControlName="p_state" class="form-control" name="p_state">
<option *ngFor="let element of state" [value]="element.state_id">{{element.state_name}}</option>
</select>
<span class="text-danger" *ngIf="f.p_state.touched && f.p_state.errors?.required">Please Select
State</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label">City</label>
<select class="form-control" formControlName="p_city">
<option *ngFor="let element of city" [value]="element.city_id">{{element.city_name}}</option>
</select>
<span class="text-danger" *ngIf="f.p_city.touched && f.p_city.errors?.required">Please Select City</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label">County</label>
<select class="form-control" formControlName="p_county">
<option *ngFor="let element of county" [value]="element.county_id">{{element.county_name}}</option>
</select>
<span class="text-danger" *ngIf="f.p_county.touched && f.p_county.errors?.required">Please Select
County</span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label">Zip Code</label>
<input formControlName="p_zipcode" type="text" class="form-control" placeholder="Zip Code">
<span class="text-danger" *ngIf="f.p_zipcode.touched && f.p_zipcode.errors?.required">Please enter Zip
Code.</span>
</div>
</div>
</div>
<div style="text-align: center;">
<button class="btn btn-primary" type="submit" (click)="addCompany()">Submit</button>
</div>
</form>
</div>
Я инициализирую форму, как показано ниже,
form = new FormGroup({
p_county: new FormControl('', Validators.required),
p_country: new FormControl('', Validators.required),
p_city: new FormControl('', Validators.required),
p_state: new FormControl('', Validators.required),
p_zipcode: new FormControl('', Validators.required),
//usr_lname:new FormControl('', [Validators.required, Validators.email]),
});
Моя функциональность здесь
getDDlistName(listname: string) {
this.ddlist.getDDlist(listname).subscribe(response => {
if (response.success) {
this.ddlistname = response.data;
} else {
this.router.navigate(['/error']);
}
});
}
getStateDDList(code: string) {
this.ddlist.stateDropDown(code).subscribe(response => {
if (response.success) {
this.state = response.data;
}
else {
this.toastr.info('NO DD Data')
}
});
}
getCityDDList(code: string) {
this.ddlist.cityDropDown(code).subscribe(res => {
if (res.success) {
this.city = res.data;
} else {
this.toastr.info('NO DD data', 'Client')
}
})
}
getCountyDDList(code: string) {
this.ddlist.countyDropDown(code).subscribe(res => {
if (res.success) {
this.county = res.data;
} else {
this.toastr.info('NO DD data', 'Client')
}
})
}
getCountryDDList(code: string) {
this.ddlist.countryDropDown(code).subscribe(res => {
if (res.success) {
this.country = res.data;
} else {
this.toastr.info('NO DD data', 'Client')
}
})
}
addCompany() {
console.log('form', this.form)
if (this.form.valid) {
this.isSubmitted = true;
this.gc.addCompany(JSON.stringify(this.form.value)).subscribe(response => {
if (response.success) {
if (this.form.controls['p_active'].value == false) {
this.toastr.success('DeActivated Successfully', 'Client');
}
this.toastr.success('Saved Successfully', 'Client');
this.router.navigate(['/default/adduser/search']);
this.form.reset();
}
else {
this.isSubmitted = false;
this.toastr.error(response.errorMessage, 'Client');
}
});
} else {
// this.isSubmitted = false;
this.toastr.error('Required Field information is not available. Please enter required information in highlighted fields as below.');
this.validateAllFormFields(this.form);
}
return;
}
getCompanies() {
this.getDDlistName("Company_Type");
this.getStateDDList('ST');
this.getCityDDList('CT');
this.getCountyDDList('CY');
this.getCountryDDList('CNT');
let obj = localStorage.getItem('currentuser');
this.allCompanies.p_comp_id = JSON.parse(obj).comp_id;
this.allCompanies.p_level = 2;
this.allCompanies.p_usr_id = JSON.parse(obj).usr_id;
this.gc.getCompanies(this.allCompanies).subscribe(response => {
if (response.success) {
let data = response.data.filter(value1 => {
if (parseInt(value1.comp_id) == parseInt(this.url[4])) {
return value1;
}
});
let type = this.ddlistname.filter(response => {
if (response.dd_det_id == data[0].comp_type) {
return response;
}
});
let city = this.city.filter(value => {
if (value.city_name == data[0].city_name) {
return value;
}
})
let county = this.county.filter(value => {
if (value.county_name == data[0].county_name) {
return value;
}
});
let country = this.country.filter(value => {
if (value.country_name == data[0].country_name) {
return value;
}
});
let state = this.state.filter(value => {
if (value.state_name == data[0].state_name) {
return value;
}
});
this.form.get('p_zipcode').setValue(data[0].comp_zip);
this.form.get('p_comp_address').setValue(data[0].comp_address);
this.form.get('p_comp_address1').setValue(data[0].comp_address1);
this.form.get('p_admin_pswd').setValue(data[0].usr_pswd);
this.form.get('p_active').setValue(data[0].active);
this.form.controls['p_state'].setValue(state[0].state_id, { onlySelf: true });
//this.form.value.p_state = state[0].state_id;
this.form.controls['p_comp_type'].setValue(type[0].dd_det_id, { onlySelf: true });
//this.form.value.p_comp_type = type[0].dd_det_id;
this.form.controls['p_city'].setValue(city[0].city_id, { onlySelf: true });
//this.form.value.p_city = city[0].city_id;
this.form.controls['p_country'].setValue(country[0].country_id, { onlySelf: true });
//this.form.value.p_country = country[0].country_id;
this.form.controls['p_county'].setValue(county[0].county_id, { onlySelf: true });
//this.form.value.p_county = county[0].county_id;
this.form.get('p_usr_id').setValue(JSON.parse(localStorage.getItem('currentuser')).usr_id);
} else {
this.toastr.error('Something went Wrong Pls Check System Admin', 'Client');
}
});
}