I'm a angular2 newbie and I have a question about getting data back from a template. I have the following template:
<h2>Set parameters</h2>
<button (click)="onClick()">Calculate</button>
<h3>Sailing profiles</h3>
<label *ngFor="let sailingProfile of sailingProfiles">
<input type="checkbox" name="{{sailingProfile.title}}" value="{{sailingProfile.title}}">
{{sailingProfile.title}}<br>
</label>
<h3>Counters</h3>
<label *ngFor="let counter of counters">
<input type="checkbox" name="{{counter.type}}" value="{{counter.type}}">
<input type="text"> {{counter.type}}<br>
</label>
The purpose is to select one ore more sailing profiles and select one ore more counters and add a value for each selected counter. The component which uses this template is:
import {Component, EventEmitter, Output} from "@angular/core";
import {CounterService} from "../service/counter.service";
import {SailingProfileService} from "../service/sailing-profile.service";
import {CounterModel} from "../model/counter";
import {SailingProfileModel} from "../model/sailing-profile";
@Component({
selector: 'params',
templateUrl: '../../template/params.html',
providers: [CounterService, SailingProfileService],
})
export class ParamsComponent {
@Output() paramsUpdated: EventEmitter<string> = new EventEmitter<string>();
counters: CounterModel[] = [];
sailingProfiles: SailingProfileModel[] = [];
constructor(private counterService: CounterService, private sailingProfileService: SailingProfileService) {
}
ngOnInit() {
this.counterService.getCounters().subscribe(c => this.counters = c);
this.sailingProfileService.getSailingProfiles().subscribe(s => this.sailingProfiles = s);
}
onClick() {
this.paramsUpdated.emit('test');
}
}
How do I get the selected sailing profiles and counters with their values back in the onClick() method? The desired result is a string which looks like this:
{"counters":[{"type":"Running hours","value":6000},{"type":"Seconds","value":31536000}],"sailing_profiles":[{"title": "Continuous sailing"}]}
Use [(ngModel)]
instead of value
It will look something like this
<label *ngFor="let sailingProfile of sailingProfiles">
<input type="checkbox" name="{{sailingProfile.title}}" [(ngModel)]='sailingProfile.checkBoxState'>
{{sailingProfile.title}}<br>
</label>
<h3>Counters</h3>
<label *ngFor="let counter of counters">
<input type="checkbox" name="{{counter.type}}" [(ngModel)]='counter.checkBoxState'>
<input type="text"> {{counter.type}}<br>
</label>
Now when you access this.counter
or this.sailingProfiles
inside onClick
, you will see that checkBoxState : true
is present for every selected checkbox. It should look like
this.counters = [
{"type":"Running hours","value":6000},
{"type":"Seconds","value":31536000, checkBoxState: true}
];
this.sailingProfiles = [
{"title": "Continuous sailing", checkBoxState: true}
]
Now you can get the values of the selected objects.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments