将模板中的数据返回到组件中

时间:2016-07-29 13:42:19

标签: angular

我是一个有角度的新手,我有一个关于从模板中获取数据的问题。我有以下模板:

<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>

目的是选择一个或多个航行剖面并选择一个或多个计数器并为每个选定的计数器添加一个值。使用此模板的组件是:

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');
    }
}

如何在onClick()方法中获取所选的航海配置文件和计数器及其值?所需的结果是一个字符串,如下所示:

{"counters":[{"type":"Running hours","value":6000},{"type":"Seconds","value":31536000}],"sailing_profiles":[{"title": "Continuous sailing"}]}

2 个答案:

答案 0 :(得分:1)

使用[(ngModel)]代替value

它看起来像这样

<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>

现在,当您在this.counter内访问this.sailingProfilesonClick时,您会看到每个所选复选框都存在checkBoxState : true。它应该看起来像

this.counters = [
  {"type":"Running hours","value":6000},
  {"type":"Seconds","value":31536000, checkBoxState: true}
];

this.sailingProfiles = [
  {"title": "Continuous sailing", checkBoxState: true}
]

现在您可以获取所选对象的值。

答案 1 :(得分:0)

将其设为表单,然后您可以将数据设为form.value。最好使用@angular/forms捆绑包并在您的bootstrap中执行:

disableDeprecatedForms(),
provideForms(),

获取当前的表单API。这是关于Angular 2表单的最新教程:http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/