Setting @ViewChild dynamically



I’ve got an example working with @ViewChild statically (predefined id’s), but I want to set @ViewChild dynamically in a method so it’s more generic.

I have no idea how to.

Please have a look at my Github project:

GetElement experiment with @ViewChild

I now have @ViewChild hard-coded in the Object:

    @ViewChild("question1") question1: ElementRef;
    @ViewChild("question2") question2: ElementRef;

I would like to create them dynamically, based on the question parameter.
So replace this:

    private _checkValue(question: string, value: string) {
        // get the right StackLayout
        let container;
        switch(question) {
            case 'question1':
                container = this.question1.nativeElement;
            case 'question2':
                container = this.question2.nativeElement;

with something like this, but working. :slight_smile:

    private _checkValue(question: string, value: string) {
        @ViewChild(question) questionElem: ElementRef;
        // get the right StackLayout
        let container = questionElem.nativeElement;


Late reply. Did you take a look at @ViewChildren?

If you have something like this:

  <question id="1"></question>
  <question id="2"></question>

Now, in your ParentComponent:

import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
	selector: 'parent'
export class ParentComponent implement AfterViewInit {

    @ViewChildren(QuestionComponent) questions: QueryList<QuestionComponent>;

	ngAfterViewInit() {
		console.log('viewchildren defined: ', this.items != undefined, ', length: ', this.items.length);

			(question, i, allQuestions) => {
				console.log(' = ',;

Does this help?


Thanks, that looks promising.
I will try it out later this week!