2017-04-07 62 views
3

我有一個包含一個<input/>元素該組件添加屬性綁定和事件偵聽器的角度成分。我正在考慮允許消費組件通過跨越來指定自定義輸入字段(可能與父代)。組件中的當前WIP;角 - 屬性綁定和事件添加到transcluded元素成分

<!-- Container for the transcluded element --> 
<div #inputWrapper> 
    <ng-content></ng-content> 
</div> 

<!-- Default element to display if no element provided --> 
<ng-container *ngIf="inputWrapper.children.length == 0"> 
    <input 
    [value]="getValue()" 
    [ngClass]="options.inputClasses" 
    (click)="onClick()" 
    [attr.placeholder]="options.placeholder" 
    type="text" 
    > 
</ng-container> 

意圖是,如果組件使用像;

<my-component></my-component> 

然後將使用默認輸入,但是如果提供了自定義輸入;

<my-component> 
    <input type="text"> 
</my-component> 

然後,將使用提供的輸入。用上面的例子來說明這個功能(即自定義輸入代替)。這種額外的複雜性在於,可能自定義輸入字段可能具有父元素,例如使用Angular Material時;

<my-component> 
    <md-input-container> 
    <input mdInput placeholder="My Custom Input"> 
    </md-input-container> 
</my-component> 

什麼是工作再上一個transcluded輸入字段手柄和從默認輸入添加綁定到它(主要是[value](click)綁定,所以他們表現得像默認的最佳方式是什麼?

回答

0

更新角5

ngOutletContext更名爲ngTemplateOutletContext

也見https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

我認爲最簡單的方法是通過一個<template>(或Angular4 <ng-template>)像

<my-component> 
    <template let-item><input [value]="option.value" type="text"></template> 
</my-component> 

這種方式,你不需要<ng-content>

MyComponent

@ContentChild(TemplateRef) template:TemplateRef; 
<template [ngTemplateOutlet]="template" [ngOutletContext]="{$implicit: options}"></template> 

我不知道如何傳遞給[ngOutletContext]="..."值應完全像您的使用情況,因爲我不認爲我完全理解你的要求。