简体   繁体   English

角反应式:填充编辑表单的选择控件失败

[英]Angular reactive: Populating the select control of the edit form fails

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 hospital while the hospital is correctly displayed, the department fails.. in the console, the populated department is showing the departmentId correctly. 我是Angular的新手,我有一个使用Angular 4响应式表单的编辑表单,试图用部门填充选择,规则是从user.hospital填充医院,然后是基于医院的级联下拉部门,而医院正确显示,部门失败..在控制台中,填充的部门正确显示了DepartmentId。

edit component: 编辑组件:

    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

the Html page: 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>

the SaveDama model 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;

}

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 };
}

and the validation div 和验证div

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ng-select 禁用表单控件在反应形式角度不起作用 - ng-select disable form control not working in reactive form angular 使用来自服务器的数据填充 Angular 的响应式表单 - Populating Angular's Reactive form with data from server 正确填充角反应形式 - Populating Angular Reactive Forms correcctly Angular 7:在角度反应形式中找不到名称为 formControlName 的控件 - Angular 7: Cannot find control with name: formControlName in angular reactive form Angular Reactive Form 编辑模式,如何重新填充输入类型=文件? - Angular Reactive Form Edit Mode, How to RePopulate Input type=file? 在以角4反应形式进行控件初始化后,如何添加自定义验证? - How to add custom validation after control initialization in angular 4 reactive form? Angular - 测试响应式表单控件启用值更改 - Angular - test reactive form control enable on value changes 无法将表单控制分配给 Reactive Forms 中的模板变量 - angular? - Unable to assign form control to template variable in Reactive Forms - angular? 如何在角度反应形式控件中添加小数,其值从 1 和更大开始 - how to add decimal in angular reactive form control with value starting with 1 and greater Angular 4:使用自定义异步验证器,反应式表单控件卡在挂起的 state - Angular 4: reactive form control is stuck in pending state with a custom async validator
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM