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

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

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

问题描述

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

编辑组件:

 form = new FormGroup({医院:new FormControl({ value: 'hospitalId', disabled: true }, Validators.required),部门:new FormControl('', Validators.required));damaId:号码;我:任何;医院:任何[];所选医院:任意;部门:任何[];可用部门:任何[];所选部门:任意;用户:字符串 = '';构造函数(私有路由:ActivatedRoute,专用路由器:路由器,私人公共服务:公共服务,私人 damaService:DamaService,私人帐户端点:帐户端点,私人 toastyService: ToastyService) {this.sub = this.route.params.subscribe(参数 =>{让 id = +params['id'];this.getDama(id);});this.accountEndpoint.getUserEndpoint().订阅(响应=> {const me = response.json();this.dama.userId = me.id;});}ngOnInit() {const 来源 = [this.accountEndpoint.getUserEndpoint(),this.commonService.getHospitals(),this.commonService.getDepartments(),this.commonService.getApproves(),];this.sub = this.route.params.subscribe(参数 =>{让 id = +params['id'];this.getDama(id);});Observable.forkJoin(sources).subscribe(数据 =>{const me = data[0].json();this.me = 我;this.dama.userId = me.id;this.hospitals = 数据[1];this.departments = 数据[2];this.approves = 数据[3];this.initializeSelectedHospital();this.filterDepartments();},错误 =>{如果(错误状态== 404)this.router.navigate(['/damas']);});}ngOnDestroy(): 无效 {this.sub.unsubscribe();}getDama(id: number): void {this.damaService.getDama(id).订阅((dama: SaveDama) =>this.onDamaRetrieved(dama),(错误:任何)=>{如果(错误状态== 404)this.router.navigate(['/damas'])});}onDamaRetrieved(dama: SaveDama): void {//更新表单上的数据this.form.patchValue({医院:this.dama.hospitalId,部门:this.dama.departmentId,})}私人 initializeSelectedHospital() {this.selectedHospital = this.hospitals.find(h => h.id === this.me.hospitalId);}私人过滤器部门(){this.availableDepartments = this.selectedHospital.departments;}公共提交(){控制台日志(this.form);如果(this.form.dirty){//将表单值复制到 dama 对象值上让 p = Object.assign({}, this.dama, this.form.value);this.damaService.update(p).订阅(x => {x.toastyService.success({title: '成功',msg: '表格已成功更新.',主题:'引导',showClose: 真,超时:5000

HTML 页面:

 <div class="form-group"><label for="hospital"hospital=""></label><select id="hospital" class="form-control" formControlName="hospital" [(ngModel)]="selectedHospital"><option value="undefined">选择医院</option><option *ngFor="let h of Hospitals" [ngValue]="h">{{ h.name }}</option></选择>

<div class="form-group"><label for="department">部门:</label><select id="department" class="form-control" formControlName="department" [disabled]="!availableDepartments" [(ngModel)]="selectedDepartment"><option value="undefined" 已禁用>选择部门<span *ngIf="selectedHospital">来自{{selectedHospital?.name}}"</span></选项><option *ngFor="let d of availableDepartments" [ngValue]="d">{{d.name}}</option></选择><div *ngIf="form.get('department').touched && form.get('department').invalid" class="alert alert-danger">需要部门....<;/div>

SaveDama 模型

 导出类 SaveDama {身份证号码;部门ID:号码;医院编号:编号;damaNumb:数字;totalDisch:数量;damaDt:字符串;数据输入时间:字符串;最新更新:字符串;在:字符串;批准:字符串;批准编号:编号;笔记:字符串;用户 ID:字符串;}

感谢您的帮助.....

解决方案

功能简化为以下代码:

 function invalidDama(input: FormControl) {如果(!输入值){返回空;}const goodNumb = input.value.damaNumb 

和验证 div

 <div *ngIf="form.get('totalDisch').errors.invalidDama">放电不能小于DAMA....</div>

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.

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:

                <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

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

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

09-02 02:13