【问题标题】:Access transcluded content访问嵌入的内容
【发布时间】:2017-04-05 20:14:57
【问题描述】:

我有一个组件,用于显示嵌入在组件中的代码块

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

组件看起来像这样

code.component.ts

    @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 作为&lt;ng-content #content&gt;&lt;/ng-content&gt;。但这些都不起作用。

【问题讨论】:

标签: angular


【解决方案1】:

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

那么你就可以得到包装元素的innerHTML

@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

【讨论】:

  • 你有在底部制作这些链接的 SO web ring 插件吗?我现在在“另见”参考文献中大约有四层。 ;^D
  • @ruffin LOL 不是故意的。我只是想添加相关内容的链接以保持联系。
猜你喜欢
  • 1970-01-01
  • 2012-01-19
  • 1970-01-01
  • 2021-07-13
  • 2013-04-16
  • 2015-09-18
  • 2014-09-09
  • 2015-09-11
  • 1970-01-01
相关资源
最近更新 更多