【问题标题】:angular 5 populate form fields using other field values if checkbox is selected如果选中复选框,则角度 5 使用其他字段值填充表单字段
【发布时间】:2019-03-01 11:31:02
【问题描述】:

我有两部分表格 - 通讯地址和居住地址。目标是如果选中复选框,则将值从一个字段复制/传递到另一个字段。请看下面的用例

  • 如果选中复选框(与居住地址相同),则使用居住地址表单字段的值填充通信地址字段
  • 如果选中复选框后居住地址中的任何表单字段发生更改,请将更改实时传递到通信中的字段
    地址和
  • 最后,如果未选中复选框,则清除通信地址中的表单值。以下是我尝试过的

组件.ts

populateCorrespondenceAdd(event) {
    //console.log(event.checked)
    if (event.checked) {
        [...]
        this.correspondenceHouseNumber = 
        this.residentialHouseNumber;
        this.correspondenceStreetName = 
        this.enrollee.residentialStreetName;
        this.enrollee.correspondenceLGA = 
        this.enrollee.residentialLGA;
        [...]
    }
}

component.html

<mat-checkbox [(ngModel)]="populateCorrespondenceaddress" (change)="populateCorrespondenceAdd($event)"
                formControlName="populateCorrespondenceadd" value="true">Same as residential address?)</mat-checkbox>

上面的代码不太符合预期,因为 (i) 取消选中复选框不会清除表单字段 (ii) 选中复选框后,如果住宅中的任何表单字段有任何更改地址部分,通信表单字段不会更新以反映更改。 N:B:字段位于一个表单组中

请指导。

【问题讨论】:

标签: angular typescript angular5 angular-forms


【解决方案1】:

我已经简化了您的示例并使用了:
- 发送地址
- 帐单地址

否则我认为它几乎相同:)

TS

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormControl } from '@angular/forms';
import { EMPTY } from 'rxjs';
import { tap, distinctUntilChanged, switchMap, startWith } from 'rxjs/operators';

interface Address {
  street: string;
  city: string;
  country: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  public isSameAddressControl: FormControl = new FormControl(false);

  public addresses: FormGroup = this.fb.group({
    sendingAddress: this.fb.group({
      street: '',
      city: '',
      country: ''
    }),
    billingAddress: this.fb.group({
      street: '',
      city: '',
      country: ''
    })
  });

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.isSameAddressControl
      .valueChanges
      .pipe(
        distinctUntilChanged(),
        switchMap(isSameAddress => {
          if (isSameAddress) {
            return this.addresses
              .get('sendingAddress')
              .valueChanges
              .pipe(
                // at the beginning fill the form with the current values
                startWith(this.addresses.get('sendingAddress').value),
                tap(value =>
                  // every time the sending address changes, update the billing address 
                  this.addresses
                    .get('billingAddress')
                    .setValue(value)
                )
              )
          } else {
            this.addresses
              .get('billingAddress')
              .reset();

            return EMPTY;
          }
        })
        // don't forget to unsubscribe when component's destroyed
      )
      .subscribe();
  }
}

HTML

<input type="checkbox" [formControl]="isSameAddressControl"> Same address for sending/billing

<form [formGroup]="addresses">
  <ng-container formGroupName="sendingAddress">
    Sending address<br>
    <input type="text" formControlName="street" placeholder="Street" autocomplete="off"><br>
    <input type="text" formControlName="city" placeholder="City" autocomplete="off"><br>
    <input type="text" formControlName="country" placeholder="Country" autocomplete="off"><br>
  </ng-container>

  <ng-container formGroupName="billingAddress">
    Billing address<br>
    <input type="text" formControlName="street" placeholder="Street" autocomplete="off"><br>
    <input type="text" formControlName="city" placeholder="City" autocomplete="off"><br>
    <input type="text" formControlName="country" placeholder="Country" autocomplete="off"><br>
  </ng-container>
</form>

这是 Stackblitz 上的一个工作示例:https://stackblitz.com/edit/angular-nyjsnt

【讨论】:

  • 感谢您的指导。我如何将此示例与 rxjs 5.5.2 一起使用。我似乎无法让它工作
  • 你必须链接对可观察对象的调用而不是管道(但你应该升级......)
  • 请您指导如何使用链而不是管道。谢谢
  • 想知道为什么有人对我的回答投了反对票。我很高兴得到解释:)
猜你喜欢
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-25
  • 2011-06-05
  • 1970-01-01
  • 2023-03-16
  • 2019-05-13
相关资源
最近更新 更多