【问题标题】:How to pass back data from parent component to child component in angular如何以角度将数据从父组件传回子组件
【发布时间】:2020-09-22 23:14:46
【问题描述】:

我在我的子组件中使用 Google Place Autocomplete,但是当每个输入都填充数据时,父组件没有得到更改,因此我无法发布到服务器有效数据。

我有一个在父组件中调用的子组件:

<rc-billing-data *ngIf="accountData"
      [clientRegion]="accountData.region"
      [(currencyModel)]="accountData.currency"
      [currenciesModel]="accountData.currencies"
      [(billingLanguageModel)]="accountData.billingLanguage"
      [localeModel]="accountData.locales"
      [(autoPaymentModel)]="accountData.enableAutoPayment"
      [(countryModel)]="accountData.country"
      [billingCountriesModel]="accountData.billingCountries"
      [(zipModel)]="accountData.zip"
      [(cityModel)]="accountData.city"
      [(addressNameModel)]="accountData.addressName"
      [(addressTypeModel)]="accountData.addressType"
      [(addressNumberModel)]="accountData.addressNumber"
      [(addressFloorDoorModel)]="accountData.addressFloorDoor">
    </rc-billing-data>

在子组件中google place输入调用handleAddressChange函数:

<label for="googleAddress">Pontos cím keresése</label>
        <input ngx-google-places-autocomplete
               (onAddressChange)="handleAddressChange($event)"
               id="googleAddress"
               type="text">

handleAddressChange 函数正在更改输入的值,但 accountData 没有更新。

handleAddressChange(event) {
    let address: Address;
    this.zipModel = '';
    this.cityModel = '';
    this.addressNameModel = '';
    this.addressTypeModel = '';
    this.addressNumberModel = '';
    this.addressFloorDoorModel = '';

    this.addressCoordsModel = {
      lat: event.geometry.location.lat(),
      lng: event.geometry.location.lng()
    };

    address = this.regionHelper.setAddressParts(this.clientRegion, event.address_components);

    this.countryModel = address.country;
    this.zipModel = address.zip;
    this.cityModel = address.city;
    this.addressNameModel = address.addressName;
    this.addressTypeModel = address.addressType;
    this.addressNumberModel = address.addressNumber;
  }

如果我在输入中输入手册,则它们工作正常。

【问题讨论】:

  • 父母将数据传递给具有属性的孩子,将孩子传递给具有事件的父母。你用的是什么ChangeDetectionStrategy
  • 我正在使用默认策略。

标签: angular typescript angular10


【解决方案1】:

最好在您的子组件中有一个输出事件发射器(最好有一个包含所有 AccountData 的输入)并且您的父对象需要管理此事件。例如:

家长需要这个

HTML

<child-component [accountData]="accountDataObject" (changesOnChild)="parentDetectChanges(event)" > </child-component>

ts

parentDetectChanges(newData: any){
    //put the new values here


}

孩子

@Input() accountData: AccountData;
@Output() changesOnChild = new EventEmitter<AccountData>();

....
some code
....

handleAddressChange(event) {
    //modify account data object

    ...

    this.changesOnChild.emit(this.accountData)
}


【讨论】:

    猜你喜欢
    • 2017-09-01
    • 2020-08-24
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多