有一个用户可以单击的按钮,它将添加更多地址表单字段。如果用户在字段中填写其地址信息,然后单击按钮添加更多地址,则先前的输入将被清除。如何防止按钮清除以前的条目?
component.ts文件中的片段:
ngOnInit() {
this.addresses = [];
this.addresses.push(new Address('', undefined ,'','Canada',''));
}
addAddress(){
this.addresses.push(new Address('', undefined ,'','Canada',''));
}
我的address.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>
答案 0 :(得分:0)
更好的做法是在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();
}
}