點擊添加按鈕會自動添加一個空的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>
問題解決了。。。。