Renderer multiple selectRootElement Issue

Viewed 17706

I am trying to use Renderer.selectRootElement to get some elements from my Component, as described here.

Everything works fine, unless I select only one element (plnkr).

As you can see, I have created a component:

export class ExampleComponent implements OnInit{
    @Input() start: any;
    @Input() end: any;

  constructor(public _renderer:Renderer){

  };

    ngOnChanges(){

    }
    ngOnInit(){
        console.log("NG ON CHAN START DATE",this.start);
        console.log("NG ON INIT END DATE",this.end);
        var container =  this._renderer.selectRootElement('.container');
        console.log(container);   
        var inner1 =  this._renderer.selectRootElement('.inner1');
        console.log(inner1);   
        var inner2 =  this._renderer.selectRootElement('.inner2');
        console.log(inner2);   
    }

}

When I try to run this, I have an error of :

EXCEPTION: The selector ".inner1" did not match any elements in [{{exampleData.end}} in MainViewComponent@3:65]

(however, in my app, when only the first container is found, then none others are found).

Any ideas where does this come from?

UPDATE

I found out that the directive is not invoked fully - only div with class container gets added to the HTML.

enter image description here

2 Answers

If you want to preserve content then use the second boolean parameter to true, like this: (using Angular 6)

let activeLi = this.renderer.selectRootElement('ul.ddl>li.active', true);

See the detail from API

     /*
     * Implement this callback to prepare an element to be bootstrapped
     * as a root element, and return the element instance.
     * @param selectorOrNode The DOM element.
     * @param preserveContent Whether the contents of the root element
     * should be preserved, or cleared upon bootstrap (default behavior).
     * Use with `ViewEncapsulation.ShadowDom` to allow simple native
     * content projection via `<slot>` elements.
     * @returns The root element.
     */

abstract selectRootElement(selectorOrNode: string | any, preserveContent?: boolean): any;

Thanks Eric to bring in notice that it removes content by default!

Related