数据未发送到 FormGroup - Angular

Data not being sent to FormGroup - Angular

我有一个单字段表单,数据没有发送到我的 FormGroup。出于某种奇怪的原因,当我记录它时它是空的。

我的TS文件

  addressData: FormGroup;
  submitted = false;
  success = false;

  userLat: number;
  userLng: number;

  private geoCoder: google.maps.Geocoder;

  constructor(private maps: MapsAPILoader, private bulider: FormBuilder, private ref: ChangeDetectorRef) { }

  ngOnInit() {
    this.addressData = this.bulider.group({
      address: ["", Validators.required],
    });
    console.log("Init data: " + this.addressData.controls['address'].value);

    this.maps.load().then(() => {
      this.geoCoder = new google.maps.Geocoder();
    });
  }

  getAddress() {    
    this.submitted = true;

    // I commented this out to see if the geocoder works
    // if (this.addressData.invalid) {
    //   console.error("Invalid address! Address: " + this.addressData.value);
    //   return;
    // }

    this.geoCoder.geocode({ 'address': this.addressData.controls['address'].value }, (results, status) => {
      if (status === google.maps.GeocoderStatus.OK) {
        this.userLat = results[0].geometry.location.lat();
        this.userLng = results[0].geometry.location.lng();
        this.ref.detectChanges();
        this.success = true;
      } else {
        // The address is empty, therefore gives me invalid_request
        alert('Geocode was not successful for the following reason: ' + status + " and Address: " + this.addressData.controls['address'].value);
      }
    });
    this.submitted = false;
  }
}

HTML

<div>
    <form [formGroup]="addressData" (ngSubmit)="getAddress()">
      <input class="addressBar" type="text" placeholder="Address" maxlength="30" autofocus>
      <br><br><button class="searchBtn" type="submit">Search</button>
    </form>
  </div>

我知道您可以在 HTML 中使用 #address,并将其传递给方法 getAddress(),但我想这样做,因为我将要使用用户反馈的错误消息。

预期

我希望根据需要验证地址并在地理编码器中使用。

实际:

FormGroup 为空且始终无效(无论您输入什么),因此无法在地理编码器中使用。

您需要添加formControlName

  <input type="text" formControlName="address">

引自Step 2: Associating the FormGroup model and view

Note that just as a form group contains a group of controls, the profile form FormGroup is bound to the form element with the FormGroup directive, creating a communication layer between the model and the form containing the inputs. The formControlName input provided by the FormControlName directive binds each individual input to the form control defined in FormGroup. The form controls communicate with their respective elements.

您缺少输入中的 formControl 属性

<div>
    <form [formGroup]="addressData" (ngSubmit)="getAddress()">
      <input class="addressBar"  [formControl]=addressData.controls.address type="text" placeholder="Address" maxlength="30" autofocus>
      <br><br><button class="searchBtn" type="submit">Search</button>
    </form>
  </div>