Angular如何不使用#id从ng-content中访问组件内部变量
解决方案
你可以通过以下两种方案实现无需模板引用变量直接访问app-list组件的内部属性:
方案1:使用ngTemplateOutlet传递组件上下文
这种方案需要对app-list组件做少量改造,把原本直接投影的内容改为传入模板,同时将组件自身作为上下文传递给模板:
改造ListComponent代码
@Component({ selector: 'app-list', template: ` <ng-container *ngTemplateOutlet="contentTpl; context: {$implicit: this}"></ng-container> ` }) export class ListComponent { @Input() name: string; time = 12; // 接收父组件传入的模板 @ContentChild(TemplateRef) contentTpl!: TemplateRef<any>; }
父组件使用方式
<app-list name="vlad"> <ng-template let-self> time is : {{self.time}} name is : {{self.name}} </ng-template> </app-list>
这里的let-self就是拿到我们传入的组件实例上下文,你可以改成任意你想要的变量名,比如let-list就可以用list.time访问。
方案2:自定义结构指令注入组件实例
如果你不想改动现有app-list的结构,也可以写一个极简的结构指令来自动注入当前app-list的实例:
定义指令代码
@Directive({ selector: '[listContext]', exportAs: 'listContext' }) export class ListContextDirective { constructor(public listComponent: ListComponent) {} }
父组件使用方式
<app-list name="vlad"> <ng-container *listContext="let self = listComponent"> time is : {{self.time}} </ng-container> </app-list>
这种方案不需要改动原组件代码,只需要在需要访问组件属性的投影内容外层套一层带指令的容器即可。
注意:Angular默认的投影内容的作用域属于父组件,本身无法直接访问子组件的内部属性,以上两种方案都是通过显式传递上下文的方式实现你需要的类似
self.time的访问效果,原生并没有内置this.time这种直接访问子组件属性的语法。
内容的提问来源于stack exchange,提问作者user3807476
相关产品推荐
相关产品推荐

