I have a situation where I am using a component to render different form-field components through the use of ng-template. My goal is to access a function within the last rendered component.
I have attempted to access this function using ViewChildren() annotation with both the string selector and the BaseClass that all field-components (such as text-field and select-field) extend from.
However, the variable allFields always remains empty. I have also tried accessing it using ContentChildren and the AfterContentInit lifecycle hook. Does anyone have any suggestions on how to accomplish this?
This scenario is similar to a question posed in another forum post, but unfortunately that question remains unanswered. Therefore, I decided to inquire about it here. Thank you!
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: QueryList<ElementRef>;
lastField: FieldBaseComponent;
fieldIndex: number = 0;
ngOnInit(): void {
//...
}
ngAfterViewInit(): void {
this.lastField = this.allFields?.last?.nativeElement;
}
getTemplate() {
// returns my template
}
doFunctionOnLastField() {
this.lastField?.someFunctionInsideTheField();
}
}