【问题标题】:How can I prevent form fields from being reset on button click? (typescript/angular)如何防止表单字段在按钮单击时被重置? (打字稿/角度)
【发布时间】:2019-05-30 08:59:45
【问题描述】:

用户可以单击一个按钮,该按钮将添加更多地址表单字段。如果用户在字段中填写他们的地址信息,然后单击按钮添加更多地址,则之前的输入将被清除。如何防止按钮清除以前的条目?

来自我的 component.ts 文件的片段:

  ngOnInit() {
     this.addresses = [];
     this.addresses.push(new Address('', undefined ,'','Canada',''));
  }

  addAddress(){
    this.addresses.push(new Address('', undefined ,'','Canada',''));
  }

我的地址.ts 文件:

export class Address {

    constructor(
        public streetAddress: string,
        public province: string,
        public city: string,
        public country: string,
        public postalCode: string
    ) {  }
 }

来自我的 component.html 文件的片段:

<div class="card-body"  *ngFor="let address of addresses">
  <div class="row">

    <div class="col-md-6">
      <div class="form-group">

        <input type="text" class="form-control" 
        [(ngModel)]="address.streetAddress" #streetAddress="ngModel" 
        name="streetAddress" placeholder="Apartment/House Number and Street 
        Address">

      </div>  
    </div>

    <div class="col-md-6">
      <div class="form-group">

        <input type="text" class="form-control" [(ngModel)]="address.city" 
         #city="ngModel"  name="city" placeholder="City/Town">

      </div>
    </div>

  </div>                           
</div>

<button type="button" class="btn btn-warning btn-block" id="addAddress" 
(click)="addAddress()">More Addresses</button>

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    services中存储和操作数据的更好做法

    address.service.ts

    import { Injectable } from '@angular/core';
    import { Address } from './Address';
    
    @Injectable()
    export class AddressService {
    
      constructor() { }
    
      addresses = [];
    
      addAddress(address: Address) {
        this.addresses.push(Address);
      }
    }
    

    在 addAddresses 方法中作为参数,您可以从提交的表单中提供地址 另请阅读有关如何正确管理表单here 你的 component.ts 文件可以是:

    export class AppComponent implements OnInit {
    
       addresses: Address[];
    
       form = new FormGroup({
          streetAddress: new FormControl(''),
          province: new FormControl(''),
          city: new FormControl(''),
          country: new FormControl(''),
          postalCode: new FormControl('')
      });
        constructor(private addrs: AddressService) {}
    
        ngOnInit() { 
          this.addresses = this.addrs.addresses;
        }
    
        onSubmit() {
          this.addrs.addAddress(this.form.value);
          this.form.reset();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-10
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多