要在ng-content上使用模板引用,可以使用@ContentChild装饰器来获取对ng-content的引用。以下是一个使用Angular的示例代码:
在父组件模板中,使用ng-content包装子组件,并给ng-content添加一个模板引用变量:
在子组件中,使用@ContentChild装饰器来获取对ng-content的引用:
import { Component, ContentChild, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-child',
template: `
`
})
export class ChildComponent implements AfterContentInit {
@ContentChild('contentRef') contentRef;
ngAfterContentInit() {
console.log(this.contentRef);
}
}
在上面的示例中,父组件使用ng-content将子组件的内容包装起来,并给ng-content添加了一个模板引用变量“#contentRef”。然后在子组件中使用@ContentChild装饰器来获取对ng-content的引用,然后在ngAfterContentInit钩子函数中打印出引用。
这样就可以在子组件中使用父组件传递给ng-content的内容,并对其进行操作。