2016-11-22 92 views
2

我有我使用以显示其在组件访问transcluded内容

<gs-code> console.log("Asd")</gs-code> 

组件看起来像这样

code.component.ts transcluded的代码块中的组元

@Component({ 
     selector: 'gs-code', 
     providers: [], 
     viewProviders: [], 
     templateUrl: './code.component.html', 
     styleUrls: ['./code.component.less'] 
    }) 
    export class GsCodeComponent { 
     @Input() lang: string; 
     @Input() currentLang: string; 
     @ContentChild('content') content; 
     copied(event) { 
      console.log(event); 
     } 

     ngAfterContentInit() { 
      console.log(this.content, "content"); 
     } 
    } 

code.component.html

<pre class="prettyprint"> 
    <ng-content #content></ng-content> 
</pre> 
<button class="btn btn-sm" title="Copy to clipboard" (click)="copied(content.innerHtml)"><i class="fa fa-clipboard"></i></button> 

如何获取组件中的横向文本? 我试过使用contentChild#content作为<ng-content #content></ng-content>。但这些都没有奏效。

+0

的DUP http://stackoverflow.com/questions/37573439/get-component-child-as-的innerHTML串/ 37586026#37586026 –

回答

2

<ng-content>元素永远不会被添加到DOM本身,因此添加模板变量并查询它不起作用。
您可以用另一个元素包装<ng-content>并在其中添加模板变量并使用@ViewChild()来查询此元素。

然后,你可以得到的包装元素

@Component({ 
    selector: 'item', 
    template: '<div #wrapper><ng-content></ng-content></div>'}) 
class Item implements AfterContentInit { 

    @ViewChild('wrapper') wrapper:ElementRef; 
    @Input() type:string = "type-goes-here"; 

    ngAfterContentInit() { 
     console.log(this.wrapper.nativeElement.innerHTML); // or `wrapper.text` 
    } 
} 

参见Get component child as string