gpt4 book ai didi

angular - 结构指令 - 找到它所在的元素

转载 作者:太空狗 更新时间:2023-10-29 16:55:18 24 4
gpt4 key购买 nike

对于结构指令,我如何获取指令所在的( native )元素?使用普通指令,ElementRef 将它的 nativeElement 指向它 - 例如:

<input type="text" example>

@Directive({
selector: '[example]'
})
export class ExampleDirective {

constructor( private el: ElementRef) {}

ngAfterViewInit() {
console.log(this.el.nativeElement); // the input
}
}

但是对于结构指令,它指向模板注释 - 例如。

<input type="text" *example>

@Directive({
selector: '[example]'
})
export class ExampleDirective {

constructor(
private el: ElementRef,
private view: ViewContainerRef,
private template: TemplateRef<any>
) {}

ngAfterViewInit() {
this.view.createEmbeddedView(this.template);

console.log(this.el.nativeElement); // template bindings comment
// how to find the input itself?
}
}

我已经尝试使用 ViewContainerRef、TemplateRef、@ContentChild、@ViewChild 的各种组合 - 只是似乎无法找到输入元素本身......

最佳答案

所有结构指令都添加到<ng-template>元素。 Angular 从不添加 <ng-template>元素到 DOM。因此,不可能获取添加了结构指令的元素。

如果使用 * 的速记语法喜欢

<div *ngIf="..."></div>

Angular 创造

<ng-template [ngIf]="...">
<div></div>
</ng-template>

因为 <ng-template>未添加,无法获取它,因为 <div>不是结构指令添加到的元素您也无法使用指令引用获取此元素。

关于angular - 结构指令 - 找到它所在的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41299046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com