Angular通过ngTemplateOutlet在投影模板中获取元素到自定义属性指令的引用



我在修改自定义属性指令上的css和点击事件时遇到了问题

所讨论的DIV位于对"投影"的引用中,并传递给嵌套的子对象。

下面是它的工作原理

将ng-template添加到父模板中。

<parent>
<ng-template #editCellTemplate>
<div customUpdateDirective>Update</div>
</ng-template>
<Child1>
<Child2>
<Child3> RENDER editCellTemplate IN HERE </Child3>
</Child2>
</Child1>
</parent>

父节点通过一个可观察对象

#editCellTemplate的引用传递给child3
export class Parent {
// ...
@ContentChild('editCellTemplate') public editCellTemplate?: TemplateRef<any>;
// ...parent
ngAfterViewInit() {
if (this.editCellTemplate)
this.editService.updateEditCellTemplate(this.editCellTemplate);
}
}

customUpdateDirective:

@Directive({
selector: '[customUpdateDirective]',
})
export class CustomUpdateDirective {
constructor(public el: ElementRef) {
console.log(el); //issue here is el is a reference to the parent component and not the div the attribute is attached to.
}
}

在child3中,我有这个html来渲染对循环中的editCellTemplate的引用:

<Child3>
<!-- this renders the template in a for loop. Everything displays correctly -->
<div *ngfor...>
<ng-container *ngTemplateOutlet="editCellProjectedTemplate"> </ng-container>
</div>
</Child3>

问题是当我引用指令customUpdateDirective时,它是对ParentComponent的引用,而不是Div

@Component({
// ...
providers: [CustomUpdateDirective],
})
export class Child3 implements OnInit {
editCellProjectedTemplate!: TemplateRef<any> | null;
private customUpdateDirective: CustomUpdateDirective;
onInit() {
this.editService.editTemplateObservable.subscribe((editTemplate) =>
this.setEditTemplate(editTemplate)
);
}
setEditTemplate(template: TemplateRef<any>) {
if (Object.keys(template).length < 1) return;
//setting the template renders the div inside of editCellProjectedTemplate for Child3
this.editCellProjectedTemplate = template;
//the problem starts here
this.customUpdateDirective.el.nativeElement; //nativeElement is the a reference to the Child3 container and not the div it's instantiated on
}
}

在引用模板时,我如何获得对customUpdateDirective应用于的元素<div customUpdateDirective>Update</div>的引用?我想添加一个点击事件和样式的css。

这是一个堆栈闪电战我使用DI来传递演示的模板,而不是一个可观察对象。我怎样才能在SB示例中使用editDirective访问自定义元素?

AppModule中,通过declarationsexports注册directive,使其可用于应用程序中的其他组件

@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [
...
Child4Component,
EditDirective,
],
exports: [EditDirective],
bootstrap: [AppComponent],
})
export class AppModule {}

你也可以从子组件

中删除providers: [EditDirective],

最新更新