我有一个组件,我用它来显示嵌入在组件中的代码块
<gs-code> console.log("Asd")</gs-code>
Run Code Online (Sandbox Code Playgroud)
该组件看起来像这样
代码.组件.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");
}
}
Run Code Online (Sandbox Code Playgroud)
代码.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>
Run Code Online (Sandbox Code Playgroud)
如何获取组件中嵌入的文本?我尝试过使用contentChildand#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`
}
}
Run Code Online (Sandbox Code Playgroud)
另请参阅获取组件子级作为字符串