如何使用Angular2 CheckboxControlValueAccessor?

时间:2016-09-08 05:07:31

标签: angular angular2-forms

任何人都可以帮我在Angular2中实现CheckboxControlValueAccessor吗?任何人都可以分享一些使用CheckboxControlValueAccessor的例子吗?

我有一个从API检索的JSON 即

{"prefer":[{"name":"Send me Offers and Letters","preferenceId":"OffersAndLetter","selected":"Y"},{"name":"Need monthly reports","preferenceId":"monthlyReports","selected":"N"}],"comments":null,"status":"SUCCESS","errorDetails":[]}

现在我需要创建一个组件和相关模板,动态创建表单/复选框字段并将所选值作为N或Y访问。我还需要按用户跟踪选择更改。

组件文件是:

@Component({
selector: 'ae-preferencesdata',
moduleId: module.id,
templateUrl: './preferences.html',
directives: [REACTIVE_FORM_DIRECTIVES, ControlMessages],
providers: [SavePreferences]})

export class PreferencesComponent {
public editPreferencesForm: any;
OffersAndLetter: boolean;
monthlyReports: boolean;

public _preferencesValue: Preferences = new Preferences();
constructor(private _formBuilder: FormBuilder, private _router: Router,
    private _routeParams: RouteParams, public _editService: EditPreferences) { }

ngOnInit() {
    this.editPreferencesForm = this._formBuilder.group({
        'OffersAndLetter': this.OffersAndLetter,
        'monthlyReports': this.monthlyReports
    });
}

public populatingFields() {
    if (this.OffersAndLetter !== undefined) {
        this._preferencesValue.OffersAndLetter =
            this.OffersAndLetter === true ? 'Y' : 'N';
    } else {
        this._preferencesValue.OffersAndLetter = $('#OffersAndLetter').val();
    }
    if (this.monthlyReports !== undefined) {
        this._preferencesValue.monthlyReports =
            this.monthlyReports === true ? 'Y' : 'N';
    } else {
        this._preferencesValue.monthlyReports = $('#monthlyReports').val();
    }
}

public savePreferences() {
    this.populatingFields();
    let resp = this._editService.updateSchemePreferences(this._preferencesValue, workFlowStepCode,
        parseInt(this._workflowActivityNo));
    resp.subscribe(
        data => {
            if (data.status === 'SUCCESS') {
                formSubmitted = true;
            }
        },
        error => {
            let errorText = error.text();
            this._serverError = error.text().replace(/"/g, '');
        }
        });
}

public updateField(data) {
    let targetID = data.target.id;
    if (targetID === 'OffersAndLetter') {
        this.OffersAndLetter = data.target.checked;
    } else if (targetID === 'monthlyReports') {
        this.monthlyReports = data.target.checked;
    }

}

private setDefaultValues() {
    this.OffersAndLetter = undefined;
    this.monthlyReports = undefined;
}}

模板摘录如下:

< td *ngFor="let subattribute of prefer" >< input  type="checkbox" name="{{subattribute.preferenceId}}{{subattribute.name}}" id="{{subattribute.preferenceId}}"
(change)="updateField($event)" class="i-checks m-l-mds" [value]="subattribute.selected"
></ td>

1 个答案:

答案 0 :(得分:-3)

使用这种方式获取Angular2中的选中复选框值:

@Component({
    selector: 'checkbox',
    template : `
    <ul>
    <li *ngFor="let chk of chkArray">
        <input type="checkbox" (change)="selectChk($event,chk.id)" />
        <span>{{chk?.title}}</span>
    </li>
    </ul>
  `,
})

export class CheckboxComponent{ 

    private chkSelected: Array<any>=[];
    private chkArray:any = [
        {id:1,title:'title1'},
        {id:2,title:'title2'},
        {id:3,title:'title3'}
    ];

    selectChk(event, val){
        if(event.target.checked === true){
            this.chkSelected.push(val);
        }else{
            var index = this.chkSelected.indexOf(val);
            this.chkSelected.splice(index, 1);
        }
        console.log(this.chkSelected)
    }

}