【问题标题】:Populate FormGroup with null value and用空值填充 FormGroup 和
【发布时间】:2016-10-04 04:09:32
【问题描述】:

在 Chrome 控制台中出现错误:异常:错误:未捕获(承诺中):TypeError:无法读取 null 的属性“applicationName”。

型号: 导出类 BasicInfoModel {

    applicationName: string;
    localDirectoryPath: string; 
}

控制器向父组件发送数据,父组件在那里保存到服务。

控制器:

import { Component, Output, OnInit, EventEmitter} from '@angular/core';
import { FormGroup, FormControl, REACTIVE_FORM_DIRECTIVES, Validators,               
FormBuilder, FormArray}from "@angular/forms";
import { Observable } from "rxjs/Rx";
import { BasicInfoModel } from '../basicinfomodel';
import { BasicInfoService} from '../app.dev.basicinfo.service';

@Component({
   selector: 'basic-info',
   templateUrl: './basicInfo.html',
   styleUrls: ['../../ComponentStyles.css'],
   directives: [REACTIVE_FORM_DIRECTIVES]
})

export class BASIC_INFOComponent implements OnInit {

observableBasic: BasicInfoModel;
basicInfoForm: FormGroup;

@Output() basicInfoUpdate = new EventEmitter<JSON>();
@Output() basicInfoFormValid = new EventEmitter<Boolean>();

constructor(private formBuilder: FormBuilder, private BasicInfoService:      
BasicInfoService) {  }

onSubmit() {
    debugger;
    this.observableBasic;
    this.basicInfoUpdate.emit(this.basicInfoForm.value);
}

ngOnInit() {

    this.basicInfoForm = new FormGroup({
        'applicationName': new FormControl('', Validators.required),
        'localDirectoryPath': new FormControl('', Validators.required)
    });

    this.basicInfoForm.valueChanges.subscribe(data => console.log('form   
    changes', data));
    this.BasicInfoService.currentBasicInfo
        .subscribe(
        (basic: BasicInfoModel) => {
            this.observableBasic = basic;
        });

    (<FormGroup>this.basicInfoForm).setValue(this.observableBasic, { onlySelf: true });
}

}

我想要达到的目标:

  1. 当我构建我的代码时,我希望我的 formGroup 应该填充空值。
  2. 当我填写数据并将其保存到我的服务中的 behaviorSubject 时,稍后当我重新访问该页面时,我的 formGroup 应该与数据服务同步。

【问题讨论】:

    标签: javascript angular rxjs5 angular-material2


    【解决方案1】:

    通过添加: (this.observableBasic != undefined)

    修改了控制器
    ngOnInit() {
        this.basicInfoForm = new FormGroup({
            'applicationName': new FormControl('', Validators.required),
            'localDirectoryPath': new FormControl('', Validators.required)
        });
    
        this.BasicInfoService.currentBasicInfo
            .subscribe((basic: BasicInfoModel) => { this.observableBasic = basic; });
    
        if (this.observableBasic != undefined) {
            (<FormGroup>this.basicInfoForm).setValue(this.observableBasic, { onlySelf: true });
        }      
    
        this.basicInfoForm.valueChanges.subscribe(data => console.log('form changes', data));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多