点击添加按钮会自动添加一个空的input组
html
<div class="form-inline"> <label class="form-control-label">属性</label> <button type="button" class="btn btn-test" (click)="addProperty()">添加</button> </div> <div class="properties" *ngIf="options.properties"> <div class="property-inline" *ngFor="let property of options.properties; let idx=index"> <div class="form-inline" > <label class="form-control-label"></label> <div class="input-group"> <div class="form-inline"> <input type="text" class="property-input" name="proName_field" [(ngModel)]="property.name"> <input type="{{property.secret ? 'password' : 'text'}}" class="property-input" name="proValue_field" [(ngModel)]="property.value" > <input type="checkbox" [(ngModel)]="property.secret" name="secret_field"> <a (click)="deleteProperty(idx)"><i class="fa fa-trash color-red"></i></a> </div> </div> </div> </div> </div>
js
addProperty() { const tempProperty = { name: '', value: '' }; if (!this.options.properties) { this.options.properties = []; } this.options.properties.push(tempProperty); } deleteProperty(index) { this.options.properties.splice(index, 1); }
出现的问题是,当我在第一行input中分别添加上数据xxx,ddd后,再次点击添加按钮,此时页面刷新,添加一个空的input行,此时有两行,而第一行input中填好的值却不见了,查看元素它的model属性明明又是绑定了刚输入的值的,页面上怎么没有显示呢?
通过查阅资料了解到在ng2表单中使用ngModel需要注意,必须带有name属性或者使用 [ngModelOptions]=”{standalone: true}”,二选其一,再看我的html代码中我把显示name的input的name属性设置为一个定值,这样再经过*ngFor后,显示不同name值的input的name属性都是一样的,是不是这个原因导致的呢,于是就试着把每个input的name属性设为不一样的值:
<div class="form-inline"> <label class="form-control-label">属性</label> <button type="button" class="btn btn-test" (click)="addProperty()">添加</button> </div> <div class="properties" *ngIf="options.properties"> <div class="property-inline" *ngFor="let property of options.properties; let idx=index"> <div class="form-inline" > <label class="form-control-label"></label> <div class="input-group"> <div class="form-inline"> <input type="text" class="property-input" [name]="'proName_field' + idx" [value]="property.name" [(ngModel)]="property.name"> <input type="{{property.secret ? 'password' : 'text'}}" class="property-input" [name]="'proValue_field'+idx" [(ngModel)]="property.value" > <input type="checkbox" [(ngModel)]="property.secret" [name]="'secret_field'+idx"> <a (click)="deleteProperty(idx)"><i class="fa fa-trash color-red"></i></a> </div> </div> </div> </div> </div>
问题解决了。。。。