How to create @ViewChild temporary variable in a method in Angular 2?

11,823

You can't use ViewChild with HTML added dynamically.

ViewChild only works with component or directive types or template variables added statically to a components template.

You also can't add @ViewChild() inside a method. It works only on class-level properties and has to be added statically as well.

Components and directives are also instantiated for HTML statically added to a components template.

You can use ViewContainerRef.createComponent() to add components dynamically though. For an example see Angular 2 dynamic tabs with user-click chosen components

Share:
11,823
sudhir
Author by

sudhir

Updated on June 14, 2022

Comments

  • sudhir
    sudhir almost 2 years

    I', trying to add a html control dynamically to div and after creating the control I would like to perform operations on it by creating viewchild

     @ViewChild('dropDownListReference') myDropDownList: typeOfComponent
    

    able to create in class but in a method after generating the control cannot initialize this

    AddLevelClick() {
    var el: HTMLElement = document.getElementById('multi-sort-body');
    el.innerHTML = "<div #test1></div>";
     @ViewChild('test1') myDropDownList: typeOfComponent    // Unable to create here
    }
    

    Any clue on creating ViewChild element locally?

  • sudhir
    sudhir over 7 years
    is NgComponentOutlet out ?? I'm using Angular 2.0 Final Release
  • Günter Zöchbauer
    Günter Zöchbauer over 7 years