Skip to content

ViewContainerRef throws an error when it doesn't have views and indexOf is called #13207

Description

@alex-okrushko

I'm submitting a ... (check one with "x")

[ x ] bug report => search github for a similar issue or PR before submitting
[ ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question

Current behavior
When calling ViewContainerRef is empty and calling viewContainerRef.indexOf(someViewRef) results in

Uncaught TypeError: Cannot read property 'indexOf' of undefined
at ViewContainerRef_.indexOf

Expected behavior
I expect -1 to be returned, same as for array.indexOf() when element is not found.

the actual error is because this._element.nestedViews are not validated to be present.
actual code

indexOf(viewRef: ViewRef): number {
    return this._element.nestedViews.indexOf((<ViewRef_<any>>viewRef).internalView);
  }

this is what should be instead:

indexOf(viewRef: ViewRef): number {
  const views = this._element.nestedViews;
  return isPresent(views) ? views.indexOf((<ViewRef_<any>>viewRef).internalView) : -1;
}

or

indexOf(viewRef: ViewRef): number {
  return this.length ? views.indexOf((<ViewRef_<any>>viewRef).internalView) : -1;
}

What is the motivation / use case for changing the behavior?

I have a clean ViewContainer and I either insert() or detach() component based of some factors.
Initially the component is detached, I create component via

let compRef = this.factoryResolver.resolveComponentFactory(MyComponent)
    .create(this.viewContainerRef.parentInjector);

not via

let compRef = this.viewContainerRef.createComponent(
    this.factoryResolver.resolveComponentFactory(MyComponent))

The latter automatically inserts component, which I don't need.
So I put the check to find the indexOf this component to determine if it should be removed.

  • Angular version:
    latest

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions