2016-08-12 61 views
3

我定義與標籤,佈局,自舉類等我自己<input>組件所以,當我使用這樣的組件定義:角2:訪問的屬性列表從

<my-input label="Street" [(ngModel)]="address.street"></my-input> 

然後將實例MyInputComponent ,將使用豐富的模板來生成類似:

<div class="form-group"> 
    <label class="col-sm-3 control-label">{{ label }}</label> 
    <div class="col-sm-9"> 
     <input [(ngModel)]="value" class="form-control"> 
    </div> 
</div>` 

這是偉大的工作,我可以只使用@Input訪問「標籤」屬性:

@Component({...}) 
export class MyInputComponent { 
    @Input() label = ''; 

現在這對於少數幾個屬性來說非常棒。但HTML標準<input>標籤具有幾十個屬性,如type,min,max,placeholder ......並且我不想將每個可能的屬性都定義爲MyInputComponent的@Input屬性。

相反,我想動態地遍歷<my-input>中的屬性,並將它們複製到我的模板中的<input>元素。我知道我可以在構造函數中使用ElementRef,然後訪問其nativeElement屬性訪問DOM元素的屬性列表:

constructor(eref: ElementRef) { 
    console.log("***", eref.nativeElement); 
} 

但訪問nativeElement氣餒作爲一種不好的做法有以下幾個原因(見https://angular.io/docs/js/latest/api/core/index/ElementRef-class.html)。

所以問題是:有沒有辦法直接讀取本機瀏覽器DOM訪問<my-input>的屬性列表?

同樣,一旦我以中性,非本地方式獲得屬性列表,我如何將它們傳播到我的模板中的<input>標記?

回答

2

我想你會更好地使用transclusion來包裝你的輸入到你喜歡的MyInputComponent中。看看後續的博客:

https://toddmotto.com/transclusion-in-angular-2-with-ng-content

基本上你會改變這一點:

<my-input label="Street" [(ngModel)]="address.street"></my-input> 

要這樣:

<my-input label="Street"> 
    <input [(ngModel)]="address.street"class="form-control"> 
</my-input> 

所以,你仍然可以訪問輸入的所有屬性輕鬆地獲得你想要的小裝飾。

+0

謝謝,它看起來不錯,我會閱讀文章。我聽說過有關跨越式,但從來沒有真正知道它是關於這個。 無論如何,我仍然好奇是否有一種方法可以以乾淨,中立和非本地方式訪問Angular 2組件的屬性。 –

+0

我試圖使用transclusion,但它不夠,因爲transcluded輸入還需要一些Bootstrap設置,如'class =「form-control」'。所以無論我強迫我的組件的用戶每次都添加這樣的代碼,還是回到不得不操作DOM來手動添加Bootstrap類。 –

+0

P.S.我也嘗試過'',但它對transcluded 沒有任何影響。 –