好吧,經過兩天的困惑,我設法得到了我想要的 - 這不是最優的,但它的工作原理,它看起來很簡單。整個技巧是添加一個模板變量來引用包裝器組件。
模板變成:
<wrapper-component #mySource filter="key='abcd'">
<item-viewer *ngFor="let item of mySource.itemlist" [data]="item"></item-viewer>
</wrapper-component>
一旦包裝部件已被分配給#mySource模板變量,有可能引用它和它的公共屬性在transcluded模板。
然後,只要WrapperComponent.itemlist發生變化,ngFor輸出就會相應更新。
這是我完全通用的項目可視化組件:
@Component({
moduleId: module.id,
selector: 'item-viewer',
templateUrl: '<h1>{{data.title}</h1><p>{{data.paragraph}}</p>'
})
export class ItemViewer{
@Input() data: any;
constructor() { }
}
而且這是在包裝部件:
@Component({
moduleId: module.id,
selector: 'wrapper-component',
template: '... <ng-content></ng-content> ...'
})
export class WrapperComponent{
@Input() filter: string;
itemlist: any[];
constructor() { }
ngOnInit() {
// every three seconds the component adds a new item to
// itemlist to show that it is rendered by ItemViewer
setInterval(()=> {
this.itemlist.push({ title: "title"+filter,
paragraph: "par"+ filter
});
}, 3000);
}
}
唯一的主要的錯,我可以用這個解決方案發現是,#mySource變量成爲一個全局模板變量 - 它也可以在變形之外被引用,這絕對是不受歡迎的。如果您想多次重複使用同一個方法,則需要每次更改變量名稱。
如果您有更好的想法或問題需要指出,請讓我知道。
有什麼不把它傳遞給' **和**''。您可以使用共享服務來共享數據,否則對於transcluded元素沒有簡單的方法 - 除非事先知道組件類型。 –
您好@GünterZöchbauer,感謝您的評論。我找到了解決方案,並將其作爲答案發布 - 我看到你是Angular2的專家,也許你可以告訴我,如果你看到問題的方法。謝謝! – udik
看起來不錯。 。 。 。 ..。 。 .. –