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

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

本文介绍了角反应式:填充编辑表单的选择控件失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Angular的新手,我有一个使用Angular 4反应性表单的编辑表单,试图用部门填充选择,规则是从user.hospital填充医院,然后根据医院建立一个级联的下拉部门在正确显示医院的情况下,该科失败了.在控制台中,填充的部门正确显示了DepartmentId.

I am new to Angular and I have an edit form using Angular 4 reactive forms, trying to populate the select with department, the rule is the hospital is populated from the user.hospital, then a cascading dropdown department based on the hospitalwhile the hospital is correctly displayed, the department fails..in the console, the populated department is showing the departmentId correctly.

编辑部分:

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

the SaveDama model

 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;

}

感谢您的帮助.....

I appreciate you help.....

推荐答案

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

The function is simplified with following code:

    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>

这篇关于角反应式:填充编辑表单的选择控件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:31