gpt4 book ai didi

angular - 访问嵌入的内容

转载 作者:太空狗 更新时间:2023-10-29 18:20:59 25 4
gpt4 key购买 nike

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

<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> .但是这些都没有用。

最佳答案

<ng-content>元素永远不会添加到 DOM 本身,因此添加模板变量并查询它不起作用。
你可以包装 <ng-content>与另一个元素并在那里添加模板变量并使用 @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

关于angular - 访问嵌入的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40737037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com