mardi 21 novembre 2017

Checkboxes list values in a form

I'm new to Angular 2 so I'll need your advice to achieve development I'm working on a create/update form component. I have a checkbox list with default values (checked or not, it depends about a service). Here is my code :

@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">
            
        </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 )
  }
}

My questions :

  • How can I set my default datas for my checkboxes list ?

  • Is it possible to update these defaults values when the user check or uncheck the boxes ?

  • Is a FormArray a good option to resolve my problem ?

  • And please, let me know if you seeing bads habits in my code, I don't have any returns about it ... I'm asking a lot but I'm stucked for a while now ...

PS: I'm trying to do it without existing component to improve my angular2 skills.

Thx for yours advices




Aucun commentaire:

Enregistrer un commentaire