用空值和填充FormGroup

Populate FormGroup with null value and

本文关键字:FormGroup 填充 空值      更新时间:2023-09-26

Chrome控制台出现错误:EXCEPTION: error: Uncaught (in promise): TypeError: Cannot read property 'applicationName' of null.

模型:导出类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应该填充null值。
  2. 当我填写数据并将其保存到我的服务中的行为主题时,当我重新访问页面时,我的formGroup应该与数据服务同步。

通过添加:

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