角反应形式中的打字错误

问题描述 投票:0回答:1

我从书上得到了这个代码,但是,在原始代码中,他在OnInit()方法中初始化了formgroup。 这就是为什么不存在以下错误的原因。然而,我认为这是错误的,因为他试图绕过主要问题。

原代码:

export class CityEditComponent implements OnInit {

  
  // the form model
  form! : FormGroup


  ngOnInit() {
    this.loadData();
    form = new FormGroup({
     name: new FormControl(''),
     lat: new FormControl(''),
     lon: new FormControl('')
});
  }

我认为应该是这样,但有错误:

城市界面:

export interface City {
  id: number;
  name: string;
  lat: number;
  lon: number;
}

城市编辑组件:

export class CityEditComponent implements OnInit {

  // the form model
  form = new FormGroup({
    name: new FormControl(''),
    lat: new FormControl(''),
    lon: new FormControl('')
  });

ngOnInit() {
  this.loadData();
}

loadData() {

  .. getting a city object from a backend server...

    // update the form with the city value
    this.form.patchValue(this.city); -> error because city.lan is a number and formcontrol.lan is string
  };
}

onSubmit() {
  var city = this.city;
  if (city) {
    city.name = this.form.controls['name'].value; -> error because city.name is not null and formcontrol.name maybe null
    city.lat = +this.form.controls['lat'].value; -> error: Object is possibly null
    city.lon = +this.form.controls['lon'].value;
}
angular angular-reactive-forms
1个回答
0
投票

假设您的代码中存在一些类型不匹配和空/未定义值需要处理。我已经重写了代码。检查这是否有帮助。

export class CityEditComponent implements OnInit {
    // checking whether the city is defined before trying to access its properties or assign values to it.
    city?: City;

    // the form model
    form = new FormGroup({
        name: new FormControl(null), // Initialized with null
        lat: new FormControl(null),
        lon: new FormControl(null)
    });
    ngOnInit() {
        this.loadData();
    }
    loadData() {
        // ... getting a city object from a backend server...

        // update the form with the city value
        if (this.city) {
            this.form.patchValue({
                name: this.city.name,
                lat: this.city.lat.toString(), // Convert city.lan to string
                lon: this.city.lon.toString()  // Convert city.lon to string
            });
        }
    }
    onSubmit() {
        if (this.city) {
            const nameControl = this.form.controls['name'];
            const latControl = this.form.controls['lat'];
            const lonControl = this.form.controls['lon'];
            // Adding checks to ensure that the form control values are not null before accessing them
            if (nameControl.value !== null) {
                this.city.name = nameControl.value;
            }
            if (latControl.value !== null) {
                this.city.lat = +latControl.value; // Converting string to number
            }
            if (lonControl.value !== null) {
                this.city.lon = +lonControl.value; // Converting string to number
            }
        }
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.