我正在尝试将数据填充到“技术”表单组中,但是无法做到这一点;
这里是:https://stackblitz.com/edit/angular-fzgtqc?file=src%2Fapp%2Fapp.component.ts (可复制的示例)
editTrainner(trainner: Trainner) {
this._trainnerservice.currentTrainner = Object.assign({}, trainner);
this.registrationForm.patchValue({
personal_details: { type: Object,
name: { type: Object,
first_name:this._trainnerservice.currentTrainner.personal_details.name.first_name,
last_name: this._trainnerservice.currentTrainner.personal_details.name.last_name
},
dob: this._trainnerservice.currentTrainner.personal_details.dob,
about_yourself: this._trainnerservice.currentTrainner.personal_details.about_yourself,
willingly_to_travel: this._trainnerservice.currentTrainner.personal_details.willingly_to_travel
}
});
this.addlanguages_known();
this.addTechs();
}
addlanguages_known(): any {
const control = this.registrationForm.get('personal_details.languages_known') as FormArray;
this._trainnerservice.currentTrainner.personal_details.languages_known.forEach(x => {
control.push(this.fb.control(x));
});
}
addTechs(): any {
const control = this.registrationForm.get('technologies') as FormArray;
console.log(control);
this._trainnerservice.currentTrainner.technologies.forEach(x => {
control.push(this.fb.control(x));
});
}
答案 0 :(得分:1)
您需要调用patchValue
而不是将值推入control
中。当您需要将更多控件添加到表单本身时,应将表单控件添加到formArray
。
this.registrationForm.patchValue({
technologies: this._trainnerservice.currentTrainner.technologies
});
答案 1 :(得分:1)
Angular提供了在创建时初始化FormGroup
的功能。我建议您在创建registrationForm
时初始化值,如下所示。
this.registrationForm = this.fb.group({
...
technologies: this.fb.array(
this.data.technologies && this.data.technologies.length ?
this.data.technologies.map(tech => this.addTech(tech)) : [this.addTech()]
),
...
});
addTech(tech: Technology = {costing: {}} as Technology): FormGroup {
return this.fb.group({
name: [tech.name || ''],
experience : [tech.experience || ''],
ratings : [tech.ratings || ''],
costing : this.fb.group({
freshers: [tech.costing.freshers || ''],
laterals : [tech.costing.laterals || ''],
project_specific: [tech.costing.project_specific || '']
}),
work_as_consultant: [tech.work_as_consultant || '']
});
}
您的Technology
界面看起来像这样
export interface Technology {
name: string;
experience: number;
ratings: number;
costing: Costing;
work_as_consultant: string;
}
export interface Costing {
freshers: number;
laterals: number;
project_specific: number;
}
类似地,为其他表单组创建接口,并在创建时初始化它们,如上所示。
答案 2 :(得分:0)
ngOnInit() {
this.registrationForm = this.fb.group({
personal_details : this.fb.group({
name: this.fb.group({
first_name: [''],
last_name: ['']
}),
about_yourself: [''],
dob: [''],
// lang: [''],
languages_known: this.fb.array([]),
willingly_to_travel: ['']
}),
technologies: this.fb.array([
this.addTech()
]),
certifications : this.fb.array([
this.addCertificate()
]),
});
// this.getAllTrainners();
this.editTrainner();
this.registrationForm.patchValue({
technologies: this._trainnerservice.currentTrainner.technologies
});