Skip to content
This repository has been archived by the owner on Feb 22, 2018. It is now read-only.

Component gets other component injected even if it is not a child of it. #1404

Open
rkj opened this issue Aug 28, 2014 · 4 comments
Open

Component gets other component injected even if it is not a child of it. #1404

rkj opened this issue Aug 28, 2014 · 4 comments
Milestone

Comments

@rkj
Copy link
Contributor

rkj commented Aug 28, 2014

I have two components:

@Component(selector: 'outer-component')
class OuterComponent {
}

@Component(
    selector: 'inner-component',
    publishAs: 'ctrl')
class InnerComponent {
  OuterComponent outerComponent;
  InnerComponent(this.outerComponent);
}

When the InnerComponent is created I expect it to get 'null' value if OuterComponent is not present as its parent, but it's not the case.

Here's a failing test:

group('Nested', () {
  setUp(() {
    setUpInjector();
    module((Module module) {
      module
          ..bind(OuterComponent)
          ..bind(InnerComponent)
          ;
    });
  });

  test('should not get outer component', inject((TestBed testBed) {
    setupHtml(testBed, '''<inner-component></inner-component>''');
    var html = testBed.rootElement.children.first;
    InnerComponent component = ngProbe(html).directives[0];
    expect(component.outerComponent, null);
  }));
});
@rkj
Copy link
Contributor Author

rkj commented Aug 28, 2014

This can be overcome by using: .bind(OuterComponent, toValue: null)

@rkirov
Copy link
Contributor

rkirov commented Aug 29, 2014

Yeah, that doesn't sound very intuitive. The application injector is creating the Outer component, but that job should be left only to the directive injectors.

In fact I would argue that instead of passing in null, we should throw, i.e. all injector dependencies are hard, not optional.

A dirty way to achieve that would be to add NgElement as a constructor dependency, which can only be resolved by the directive injector.

@BlackHC
Copy link
Contributor

BlackHC commented Sep 1, 2014

I tried to point out the same issue a couple of days ago (less clear than you did though). I agree that it is really confusing. Registering directives in the injector is wrong because we don't want a default instance of components to be created. Hard injector dependencies would also be better imo. Otherwise, you might get hard-to-debug NPEs now and then.

@mhevery
Copy link
Contributor

mhevery commented Oct 2, 2014

Agreed, very confusing, will be addressed in the upcoming compiler rewrite.

@naomiblack naomiblack modified the milestones: post v1.0, v1.0 Oct 3, 2014
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

5 participants