2016-12-16 63 views
1

假設這個簡單的角2應用Angular2:適用任何屬性綁定到子元素

主要成份:

@Component({ 
    selector: "app" 
}) 
@View({ 
    directives: [ChildComponent] 
    template: '<child-component></child-component>' 
}) 
export class App {} 

子組件

@Component({ 
    selector: "child-component", 
    template: '<input type="text" id="applyEverythingToMe" />' 
}) 
export class ChildComponent {} 

我們如何申請任何屬性的綁定,指令,不管怎麼樣到applyEverythingToMe輸入字段,沒有通過@Attribute,...在ChildComponent中定義所有內容?

假設例如我們希望通過

<child-component [disabled]="true"></child-component> 

的普拉克禁用輸入:https://plnkr.co/edit/kndYdGFsp8sEzCPpcKdq?p=preview

編輯:

作爲第一答案錯過了我們的實際問題,這裏是一個有點背景:

我們使用<input type="date" />並將盒中的香蕉分成()和[](例如,在此描述:https://stackoverflow.com/a/39890184/1256072)。 這當然會將每個組件與parseDate混雜在一起,而且令人煩惱的是我們不能使用[(ngModel)]。 由於我們沒有找到任何將ngModel指令擴展到例如myModelDate自動拆分[()]並應用解析方法,我們創建了自己的組件,它實現了ControlValueAccessor,因此我們可以將它與[(ngModel)]綁定。此組件模板只包含這一個輸入類型=日期字段。現在,我們希望我們自己的組件的行爲就像任何其他的輸入,所以我們可以簡單地使用<my-date [disabled]="true"/><my-date [attr.whatever]="something" />沒有通過@Input@Attribute明確定義的所有屬性,...

+0

我建議你通過英雄的旅遊工作教程,然後再提出這樣的問題,如果你仍然有它。本教程將爲您解答這個問題 - 還有更多。 –

+0

不,不幸的是它沒有。我編輯了我最初的問題,爲我們嘗試實現的目標提供了更多背景。 –

+0

'@View({''在9個月前被刪除了,你使用的是什麼Angular2版本? –

回答

0

使用@Input()裝飾上要的屬性暴露在子組件中。

例如:

import {Component, Input } from '@angular/core'; 

@Component({ 
    selector: "child-component", 
    template: '<input type="text" />' 
}) 
export class ChildComponent { 
    @Input disabled: boolean; 
} 
+0

這正是我們試圖避免的。 –