访问被排除的内容 [英] Access transcluded content

查看:68
本文介绍了访问被排除的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a componenet which i use to display a block of code which is transcluded in the component

<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作为<ng-content #content></ng-content>.但是这些没有用.

How can I get the transcluded text in the component? I have tried using contentChild and #content as the <ng-content #content></ng-content>. But these have not worked.

推荐答案

<ng-content>元素永远不会添加到DOM本身,因此添加模板变量并对其进行查询是行不通的.
您可以将<ng-content>与另一个元素包装在一起,然后在其中添加模板变量,然后使用@ViewChild()查询该元素.

The <ng-content> element will never be added to the DOM itself, therefore adding a template variable and querying for it doesn't work.
You can wrap <ng-content> with another element and add the template variable there and query this element using @ViewChild().

然后您只需获取包装器元素的innerHTML

Then you can just get the innerHTML of the wrapper element

@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`
    }
}

另请参见获取子组件字符串

这篇关于访问被排除的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆