2017-03-27 17 views
0

我正在使用許多形式的業務用戶界面,每個表單都由許多元素組成。 使用引導每個元素看起來像:Angular2 - 重用HTML

<div class="form-group"> 
    <label for="userName" class="col-sm-3 control-label">User name</label> 
    <div class="col-sm-9"> 
     <input type="text" class="form-control" id="userName" name="userName" placeHolder="User Name" [(ngModel)]="myObj.username"> 
    </div> 
</div> 

,這是省略了驗證部分... 所以這恐怕是失控的任何改動都將必須複製/粘貼到解決所有這些投入。

我已經嘗試創建一個「輸入組件」,這將是足夠聰明做適當的HTML取決於一些參數,如id,要顯示的文本,但我不能[[ngModel]]使用這個解決方案。

任何處理此問題的好方法?或者我必須接受我的厄運,並複製/粘貼到任何地方?

+1

是的,使'ngModel'工作。你需要實現'ControlValueAccessor'。如果您在使用此方法時遇到問題,請在您的代碼和您卡住的位置發帖。 –

回答

0

感謝@Günter指出一個有用的方向。

跟隨引導我發現https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html並結束了一個有效的解決方案,其中:

  • 我inputComponent.html總是[(ngModel)] = 「值」
  • inputComponent.ts有setter和值屬性的getter。

然後我可以實現getter/setter來寫入我的數據模型。


在我的形式:

<app-input [type]="'text'" [id]="'username'" [model]="mymodel" ></app-input> 

我inputComponent.html像:

<input *ngIf="type == 'text' [(ngModel)]="value" /> 

我inputComponent.ts:

get value():any{ 
    return this.model[this.id]; 
} 

set value(val){ 
    this.model[this.id] = val; 
} 

這是不完美的,因爲如果模型的值在它不會的形式之外改變但我的目的不需要它。