Setting @ViewChild dynamically


#1

Hi,

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;
                break;
            case 'question2':
                container = this.question2.nativeElement;
                break;
        }

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;

#2

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

If you have something like this:

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

Now, in your ParentComponent:

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

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

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

		this.items.forEach(
			(question, i, allQuestions) => {
				console.log('question.id = ', question.id);
			}
		);
	}
}

Does this help?


#3

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