angular - 如何使用 Angular2 CheckboxControlValueAccessor?

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

最佳答案

在 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)
    }

}

关于angular - 如何使用 Angular2 CheckboxControlValueAccessor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39382970/

相关文章:

Angular 2 : Make a directive available in the whole app

javascript - 当我尝试在 Typescript 中应用过滤器时出错

使用 angular2-jwt 的 Angular 6

angular - 不能将命名空间 "OktaAuthService"用作类型

c# - 从 JSON post 返回成功消息

javascript - 在推送对象时,我得到的所有内容都是 NULL angular2+typescript

angular - 为什么样式不应用于动态创建容器?

Angular 2 - 组件内部的 formControlName

regex - Angular 中没有空间验证器

jquery - 如何在 Angular 2 中使用日期选择器?