在下面的HTML组件BreadcrumbComponent中存在一个指令appBreadcrumbs。
<ng-template appBreadcrumbs
let-breadcrumb
let-i="index">
<li>
some stuff
</li>
</ng-template>
而这个指令有这样的代码。
@Directive({
selector: '[appBreadcrumbs]'
})
export class BreadcrumbsDirective {
constructor(
private view: ViewContainerRef,
private templateRef: TemplateRef<any>
) {
// someAttribute is a @Input attribute in BreadcrumbComponent
const attributeFromBreadcrumbComponent = this.templateRef['_parentView'].component.someAttribute;
}
在Angular 9中,'_parentView'不存在。我如何传递这个属性?我尝试了以下方法,但没有用。
<ng-template appBreadcrumbs
[someAttribute]="someAttribute"
@Directive({
selector: '[appBreadcrumbs]'
})
export class BreadcrumbsDirective {
@Input() someAttribute: string;
注意:这个指令在很多组件中都会用到。
先谢谢你!Regards。
我终于在这里找到了解决方案如何在Angular 9中从子组件中访问父组件?
没有必要将属性作为Input传给指令。
parent: BreadcrumbComponent;
constructor(
private view: ViewContainerRef,
private templateRef: TemplateRef<any>,
private store: Store<any>,
private _injector: Injector
) {
this.parent = this._injector.get<BreadcrumbComponent>(BreadcrumbComponent);
// The attributes are accesible with this.parent.someAttribute
}