2017-06-15 68 views
0

投影節點讀取的innerText爲有這樣的組件:如何從角2

<copy [value]="model.Property"></copy> 

你寫:

var copy = ng.core.Component({ 
    selector: 'copy', 
    inputs: ['value'], 
    template: '<button mdTooltip="copy" md-icon-button attr.copy="{{ value }}"><md-icon>content_copy</md-icon></button>' 
}).Class({ 
    constructor: function (element) { 

    } 
}); 

如果你想使用你的組件是這樣的:

<copy>{{ model.Property }}</copy> 

我不能讓它工作。如何從插值表達式的innerText讀取值?

+0

嘿,沒有[我的回答](https://stackoverflow.com/a/44560492/2545680)有幫助嗎? –

回答

0
<copy>{{ model.Property }}</copy> 

這是一種單向插值,從組件到HTML的單向值綁定。

model將是您的對象變量在公共範圍的組件。

model.Property中的任何值都會直接插入到DOM中。

,如果你需要有雙向裝訂(DOM更新反映在組件,下面是

<copy [(ngModel)] = "model.Property"></copy> 
1

您組件標籤之間的指定什麼叫投射節點的語法和過程被稱爲node projection

<copy>{{ model.Property }}</copy> 
     ^^^^^^^^^^^^^^^^^^^^ 
    projected content (nodes) 

這是術語從Web組件和陰影DOM域。角通過ng-content標籤支持組件模板中節點的投影。爲了達到你想要做你的Wi什麼必須在copy組件模板中使用ng-content,等待投影內容節點初始化,使用@ContentChildren訪問此節點並閱​​讀innerText。像這樣的:

@Component({ 
    selector: 'copy', 
    template: '...<ng-content></ng-content>...' 
}) 
class CopyComponent { 
    @ContentChild('v') projected; 

    ngAfterViewInit() { 
    console.log(this.projected.nativeElement.innerText); // 'some value' 
    } 
} 

@Component({ 
    selector: 'parent', 
    templates: '...<copy><span #v>{{prop}}</span></copy>...' 
}) 
class Parent { 
    prop = 'some value'; 
} 

我用TS,但它可以很容易地適應JS。