angular 2 - 复选框列表的初始状态

时间:2017-06-14 20:14:58

标签: angular checkbox

我是Angular的新手:)我正在尝试设置复选框的初始状态。 我有一个帖子和类别,其中一些已经分配到该帖子。当我导航到帖子编辑页面时,会列出所有类别,我可以选择/取消选择。我尝试实现的是在初始化时检查某些复选框(已分配给帖子的类别)。 这就是我所拥有的:

//document-edit.component.html
<div *ngFor="let category of categories">
    <div class="checkbox">
        <label>
            <input type="checkbox"
                   [checked]="checkIfCategoryAssigned(category.documents, document.id)"
                   (change)="onChange(category.id, category.name, $event.target.checked)"> {{category.name}}
        </label>
    </div>
</div>

// document-edit.component.ts
checkIfCategoryAssigned(categoryDocuments, documentId) {
    for (let document of categoryDocuments) {
        if (document.id === documentId) {
            console.log('true');
            return true;
        }
    }
}

它似乎有效,但问题是每次鼠标移动时都会调用该函数!我读过我应该使用Observable,但我不知道怎么做。 Angular文档不包括这种特定情况。

2 个答案:

答案 0 :(得分:0)

如果您想在页面加载时进行默认检查,您可以创建一个变量并在组件中将默认值设置为true,那么类似下面的内容应该有效:

组件:

public isUser: boolean = true;
public isAdmin: boolean =false;

在你的htlml:

<div class="form-group row">
  <label class="col-md-3 form-control-label" for="roles">Roles</label>
  <div class="col-md-4" >
    <label class="col-md-3 form-control-label" for="isUser">
    <input type="checkbox" class="form-control" name="isUser" [(ngModel)]="isUser" #isuser="ngModel">Can Login</label>
  </div>
  <div class="col-md-4">
    <label class="col-md-3 form-control-label" for="isAdmin">
    <input type="checkbox" class="form-control" name="isAdmin" [(ngModel)]="isAdmin" #isadmin="ngModel">Is Admin</label>
  </div>
</div>

如果您尝试根据保存的值加载,可以使用快照数据并在组件中执行以下操作:

ngOnInit(): void {
        this.user = this.route.snapshot.data['user'];
        this.isUser = this.user.roles.includes('user');
        this.isAdmin = this.user.roles.includes('admin');
}

(我在这两个例子中都使用相同的HTML文件)

答案 1 :(得分:0)

好的,我最终得到了这个。似乎是一种更好的方法:

import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from '@angular/router';
import {Location} from '@angular/common';
import 'rxjs/add/operator/switchMap';
import {Observable} from 'rxjs/Rx';
import {DocumentService} from './document.service';
import {AlertService} from '../alert/alert.service';

@Component({
    selector: 'document-edit',
    templateUrl: './document-edit.component.html',
})

export class DocumentEditComponent implements OnInit {

    public document: any;
    public categories: any;
    public categoriesArray: Array<{id: number, name: string}> = [];

    constructor(
        private documentService: DocumentService,
        private alertService: AlertService,
        private route: ActivatedRoute,
        private location: Location
    ) {}

    ngOnInit(): void {
        this.route.params
            .switchMap((params: Params) => this.documentService.getDocument(+params['id']))
            .subscribe(document => this.document = document);
        this.getCategories();
    }


    /*
     * Push categories already assigned to this document
     * to an array used in updateDocument method
     * and check already assigned categories in the template.
     */
    documentCategories(document: any, categories: any) {
        for (let documentCategory of document.categories) {
            this.categoriesArray.push({id: documentCategory.id, name: documentCategory.name});
        }           
        for (let category of categories) {
            for (let categoryDocument of category.documents) {
                if (categoryDocument.id === document.id) {
                    category.checked = true;
                }                
            }
        }
    }

    onChange(id: number, name: string, isChecked: boolean) {
        if (isChecked) {
            if (this.categoriesArray.some(x => x.name === name)) {
                return;
            } else {
                this.categoriesArray.push({id: id, name: name});
            }
        } else {
            let index: number = this.categoriesArray.indexOf(this.categoriesArray.find(x => x.name === name));
            this.categoriesArray.splice(index, 1);
        }
        return this.categoriesArray;
    }

    updateDocument(id: number, title: string, body: any) {
        let document = {id: id, title: title, body: body, categories: this.categoriesArray};
        this.documentService.updateDocument(document).subscribe(
            data => {
                this.alertService.success('Document updated.');
                return true;
            },
            error => {
                this.alertService.error("Error updating document! " + error);
                return Observable.throw(error);
            }
        );
    }

    getCategories() {
        this.documentService.getCategories().subscribe(
            data => {this.categories = data},
            err => console.error(err),
            () => this.documentCategories(this.document, this.categories)
        );
    }

    goBack(): void {
        this.location.back();
    }

}

模板:

<form>
    <div class="row">
        <div class="col-md-8">
            <div class="form-group">
                <label for="document-title">Title</label>
                <input type="text" 
                       class="form-control" 
                       id="document-title" 
                       name="document-title" [(ngModel)]="document.title">
            </div>
            <div class="form-group">
                <label for="document-body">Body</label>
                <simple-tiny
                    name="document-body"
                    elementId="document-body"
                    [(ngModel)]="document.body">
                </simple-tiny>
            </div>
        </div>
        <div class="col-md-4">
            <label>Categories</label>                           
            <div *ngFor="let category of categories">
                <div class="checkbox">
                    <label>
                        <input type="checkbox"
                               [checked]=category.checked
                               (change)="onChange(category.id, category.name, $event.target.checked)"> {{category.name}}
                    </label>
                </div>
            </div>
        </div>                        
    </div>
    <div class="row">
        <div class="col-md-12">
            <button type="submit" 
                    class="btn btn-default" 
                    (click)="updateDocument(document.id, document.title, document.body)">
                    Submit
            </button>
        </div>
    </div>
</form>