[英]Angular: Access elementRef inside an ng-template
我得到了一个组件,它通过ng-template
呈现不同的表单域组件。 现在我想访问最后一个渲染组件中的 function 。
我尝试使用带有字符串选择器的ViewChildren()
注释或所有字段组件(文本字段、选择字段)扩展自的 BaseClass 来访问它。
allFields
始终为空。 还尝试将其作为ContentChildren
和AfterContentInit
生命周期挂钩访问。 任何想法如何实现这一目标?
这很像这个问题,但仍然没有答案,所以我想我会再问一次。 谢谢
HTML
<div *ngFor="let field of fields; fieldIndex as index">
<ng-container *ngTemplateOutlet="getTemplate()"></ng-container>
</div>
<input type="button" (click)="doFunctionOnLastField()">
<ng-template #text>
<text-field #field [field]=this.fields[fieldIndex]></text-field>
<ng-template>
<ng-template #select>
<select-field #field [field]=this.fields[fieldIndex]></text-field>
<ng-template>
TypeScript
export class FormComponent implements OnInit, AfterViewInit {
@Input() fields: FieldBase[];
@ViewChild('text') text: TemplateRef<any>
@ViewChild('select') select: TemplateRef<any>
@ViewChildren('field') allFields;
lastField: FieldBaseComponent;
fieldIndex: number = 0;
ngOnInit(): void {
//...
}
ngAfterViewInit(): void {
this.lastField = this.allFields.last; //this.allFields is empty
}
getTemplate() {
// returns my template
}
doFunctionOnLastField() {
this.lastField.someFunctionInsideTheField(); //this.lastField... is undefined
}
}
只有当模板在ViewContainerRef
中呈现时,才能访问呈现的视图及其子项,所以就在这里。
使用ngTemplateOutlet
时无法获得渲染视图,因此我认为您最好的选择是复制代码并对其进行修改以满足您的要求。
getTemplate()
方法将在调用ngAfterViewInit()
之前调用。
当第一次调用getTemplate()
时,它甚至不会返回 TemplateRef,并且只有在下一个更改检测周期中,才会正确返回 TemplateRef 并呈现您的字段。 您甚至可能会遇到 ExpressionChangedAfterItHasBeenCheckedError 错误。
因此,当ngAfterViewInit
时,您的字段不会被渲染,因此this.allFields.last
将是未定义的。
尝试为text
和select
ViewChild 声明指定static
元数据属性为true
:
@ViewChild('text', { static: true }) text: TemplateRef<any>;
@ViewChild('select', { static: true }) select: TemplateRef<any>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.