ฉันเพิ่งเริ่มใช้ Angular 2 ดังนั้นฉันต้องการคำแนะนำจากคุณเพื่อให้บรรลุการพัฒนา ฉันกำลังสร้าง/อัปเดตส่วนประกอบของฟอร์ม ฉันมีรายการช่องทำเครื่องหมายที่มีค่าเริ่มต้น (จะเลือกหรือไม่ ขึ้นอยู่กับบริการ) นี่คือรหัสของฉัน:
@Component({
selector: 'app-campaign',
template: `
<form [formGroup]="campaignForm" (ngSubmit)="saveCampaign()" novalidate>
<label for="formations">Formations</label>
<ul *ngFor="let formation of formations">
<li>
<label>
<input
type="checkbox"
[attr.checked]="formation.formationCochee == 1 ? 'checked' : null">
{{formation.formation}}
</label>
</li>
</ul>
<input
type="submit"
class="btn btn-primary"
value="Save"
[disabled]="campaignForm.invalid"/>
</form
`,
styleUrls: ['./campaign.component.css'],
providers: [CampaignService, FormationService]
})
export class CampaignComponent implements OnInit {
id: number = 0;
campaignForm: FormGroup;
title: string = "New campaign";
errorMessage: any;
formations: Formation[];
constructor(
private _fb: FormBuilder,
private _campaignService : CampaignService,
private _formationService: FormationService
) {
this.campaignForm = this._fb.group({
id: ''
, description: ["", Validators.required]
// ...
});
if (this._avRoute.snapshot.params["id"]) {
this.id = parseInt( this._avRoute.snapshot.params["id"]);
}
}
ngOnInit() {
// Case : Update Form
if(this.id > 0){
this.title = 'Update';
this._formationService.selectedFormations(this.id)
.subscribe(formations =>
this.formations=formations['records']
);
}
// Case : Create Form
else {
this._formationService.listActiveFormations()
.subscribe(formations =>
this.formations=formations['records']
);
}
}
saveCampaign(){
this._campaignService.saveCampaign(this.campaignForm.value)
.subscribe(campaign => {
this._router.navigate(['campaigns']);
}, error => this.errorMessage = error )
}
}
คำถามของฉัน:
ฉันจะตั้งค่าข้อมูลเริ่มต้นสำหรับรายการช่องทำเครื่องหมายได้อย่างไร
เป็นไปได้หรือไม่ที่จะอัปเดตค่าเริ่มต้นเหล่านี้เมื่อผู้ใช้เลือกหรือยกเลิกการเลือกช่อง
FormArray เป็นตัวเลือกที่ดีในการแก้ไขปัญหาของฉันหรือไม่
และโปรดแจ้งให้เราทราบหากคุณเห็นพฤติกรรมที่ไม่ดีในโค้ดของฉัน ฉันไม่ได้รับผลตอบแทนใด ๆ ... ฉันถามมาก แต่ตอนนี้ฉันติดอยู่ระยะหนึ่งแล้ว ...
ป.ล. ฉันกำลังพยายามทำโดยไม่มีส่วนประกอบที่มีอยู่เพื่อพัฒนาทักษะ Angular2 ของฉัน
ขอบคุณสำหรับคำแนะนำของคุณ