Angular reactive:填充编辑表单的选择控件失败

时间:2017-11-27 10:11:44

标签: javascript angular angular-reactive-forms

我是Angular的新手,我有一个使用Angular 4反应形式的编辑表单,尝试用部门填充选择,规则是医院是从user.hospital填充的,然后是基于医院的级联下拉部门 当医院正确显示时,该部门失败了.. 在控制台中,填充的部门正在正确显示departmentId。

编辑组件:

    form = new FormGroup({
        hospital: new FormControl({ value: 'hospitalId', disabled: true }, Validators.required),
        department: new FormControl('', Validators.required)
);
    damaId: number;
    me: any;

    hospitals: any[];
    selectedHospital: any;
    departments: any[];
    availableDepartments: any[];
    selectedDepartment: any;
    user: string = '';



    constructor(private route: ActivatedRoute,
        private router: Router,
        private commonService: CommonService,
        private damaService: DamaService,
        private accountEndpoint: AccountEndpoint,
        private toastyService: ToastyService) {

        this.sub = this.route.params.subscribe(
            params => {
                let id = +params['id'];
                this.getDama(id);
            }
        );

        this.accountEndpoint.getUserEndpoint()
            .subscribe(response => {
                const me = response.json();
                this.dama.userId = me.id;
            });
    }

    ngOnInit() {
        const sources = [
            this.accountEndpoint.getUserEndpoint(),
            this.commonService.getHospitals(),
            this.commonService.getDepartments(),
            this.commonService.getApproves(),
        ];
        this.sub = this.route.params.subscribe(
            params => {
                let id = +params['id'];
                this.getDama(id);
            }
        );
        Observable.forkJoin(sources).subscribe(
            data => {
                const me = data[0].json();
                this.me = me;
                this.dama.userId = me.id;

                this.hospitals = data[1];
                this.departments = data[2];
                this.approves = data[3];

                this.initializeSelectedHospital();
                this.filterDepartments();
            },
            err => {
                if (err.status == 404)
                    this.router.navigate(['/damas']);
            });
    }

    ngOnDestroy(): void {
        this.sub.unsubscribe();
    }

    getDama(id: number): void {
        this.damaService.getDama(id)
            .subscribe(
            (dama: SaveDama) => this.onDamaRetrieved(dama),
            (error: any) => {
                if (error.status == 404)
                    this.router.navigate(['/damas'])
            });
    }

    onDamaRetrieved(dama: SaveDama): void {

        //Update the data on the form
        this.form.patchValue({
            hospital: this.dama.hospitalId,
            department: this.dama.departmentId,

        })
    }
    private initializeSelectedHospital() {
        this.selectedHospital = this.hospitals.find(h => h.id === this.me.hospitalId);
    }

    private filterDepartments() {
        this.availableDepartments = this.selectedHospital.departments;
    }


    public submit() {
        console.log(this.form);
        if (this.form.dirty) {
            //copy the form values over the dama object values
            let p = Object.assign({}, this.dama, this.form.value);
            this.damaService.update(p)
                .subscribe(x => {
                    x.toastyService.success({
                        title: 'Success',
                        msg: 'Form was sucessfully Updated.',
                        theme: 'bootstrap',
                        showClose: true,
                        timeout: 5000

Html页面:

                <form [formGroup]="form" (ngSubmit)="submit()">
                <div class="form-group">
                    <label for="hospital" hospital=""></label>
                    <select id="hospital" class="form-control" formControlName="hospital" [(ngModel)]="selectedHospital">
                        <option value="undefined">Select a hospital</option>
                        <option *ngFor="let h of hospitals" [ngValue]="h">{{ h.name }}</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="department">Department:</label>
                    <select id="department" class="form-control" formControlName="department" [disabled]="!availableDepartments" [(ngModel)]="selectedDepartment">
                        <option value="undefined" disabled>
                            Select a department
                            <span *ngIf="selectedHospital">from "{{selectedHospital?.name}}"</span>
                        </option>
                        <option *ngFor="let d of availableDepartments" [ngValue]="d">{{d.name}}</option>
                    </select>
                    <div *ngIf="form.get('department').touched && form.get('department').invalid" class="alert alert-danger">Department is required....</div>
                </div>

SaveDama模型

 export class SaveDama {
    id: number;
    departmentId: number;
    hospitalId: number;
    damaNumb: number;
    totalDisch: number;
    damaDt: string;
    dataEntryTime: string;
    latestUpdate: string;
    on: string;
    approvedOn: string;
    approveId: number;
    notes: string;
    userId: string;

}

我感谢你的帮助......

1 个答案:

答案 0 :(得分:0)

使用以下代码简化了该功能:

    function invalidDama(input: FormControl) {

   if (!input.value) {
       return null;
   }

   const goodNumb = input.value.damaNumb < input.value;
   return goodNumb ? null : { badNumb: true };
}

和验证div

 <div *ngIf="form.get('totalDisch').errors.invalidDama">Discharges can not be less than DAMA....</div>