2017-02-17 57 views
0

我剛剛學習Angular 2,我一直無法解決的一個問題是使用ngModel創建表單,而沒有靜態指定我綁定的屬性的名稱。ngModel的一般綁定值

我不確定克服這個問題的機制(儘管我確信它已經很普遍了),或者它在社區中的引用方式。

我的模板確實顯示鍵和值,但它不反映保存時的更新。這似乎是以動態方式引用該屬性導致綁定丟失。 (它是管道中的數據之前評估綁定屬性?)

這裏就是我堅持:

模板:

<table class="table table-responsive"> 
    <tr *ngFor="let prop of account | keyValues"> 
    <td>{{ prop.key }}</td> 

    // Problem here: 
    // if I have [(ngModel)]="prop.key", it only displays the keys 
    // if I sub in a static attribute e.g. [(ngModel)]="account.accountName" it works 
    <td><input name="{{prop.key}}" [(ngModel)]="prop.value" /></td> 
    </tr> 
</table> 

管:

@Pipe({ 
    name: 'keyValues' 
}) 
@Injectable() 
export class KeysPipe implements PipeTransform { 
    transform(value, args:string[]) : any { 
    let keys = []; 
    for (let key in value) { 
     keys.push({key: key, value: value[key]}); 
    } 
    return keys; 
    } 
} 

組件:

... boiler plate ... 

    save(): void { 
    this.accountsService.update(this.account) 
     .then(() => this.goBack()); 
    } 

    ... 

回答

0

答案是使用Angular的Dynamic Forms

您還可以利用某些庫,如PrimeFaces的PrimeNG的可編輯數據表,我強烈建議!