fix(core): allow to query content of templates that are stamped out at a different place

Previously, if a `TemplateRef` was created in a `ViewContainerRef`
at a different place, the content was not query able at all.

With this change, the content of the template can be queried
as if it was stamped out at the declaration place of the template.

E.g. in the following example, the `QueryList<ChildCmp>` will
be filled once the button is clicked.

```
@Component({
  selector: ‘my-comp’,
  template: ‘<button #vc (click)=“createView()”></button>’
})
class MyComp {
  @ContentChildren(ChildCmp)
  children: QueryList<ChildCmp>;

  @ContentChildren(TemplateRef)
  template: TemplateRef;

  @ViewChild(‘vc’, {read: ViewContainerRef})
  vc: ViewContainerRef;

  createView() {
    this.vc.createEmbeddedView(this.template);
  }
}

@Component({
  template: `
<my-comp>
  <template><child-cmp></child-cmp></template>
</my-comp>
`
})
class App {}
```

Closes #12283
Closes #12094
This commit is contained in:
Tobias Bosch
2016-11-03 15:32:44 -07:00
committed by vikerman
parent 80d36b8db4
commit f2bbef3e33
5 changed files with 110 additions and 53 deletions

View File

@ -43,7 +43,8 @@ export function main() {
NeedsContentChildWithRead,
NeedsViewChildrenWithRead,
NeedsViewChildWithRead,
NeedsViewContainerWithRead
NeedsViewContainerWithRead,
ManualProjecting
]
}));
@ -505,6 +506,25 @@ export function main() {
expect(q.query4).toBeDefined();
});
});
describe('query over moved templates', () => {
it('should include manually projected templates in queries', () => {
const template =
'<manual-projecting #q><template><div text="1"></div></template></manual-projecting>';
const view = createTestCmpAndDetectChanges(MyComp0, template);
const q = view.debugElement.children[0].references['q'];
expect(q.query.length).toBe(0);
q.create();
view.detectChanges();
expect(q.query.map((d: TextDirective) => d.text)).toEqual(['1']);
q.destroy();
view.detectChanges();
expect(q.query.length).toBe(0);
});
});
});
}
@ -751,3 +771,18 @@ class MyComp0 {
@Component({selector: 'my-comp', template: ''})
class MyCompBroken0 {
}
@Component({selector: 'manual-projecting', template: '<div #vc></div>'})
class ManualProjecting {
@ContentChild(TemplateRef) template: TemplateRef<any>;
@ViewChild('vc', {read: ViewContainerRef})
vc: ViewContainerRef;
@ContentChildren(TextDirective)
query: QueryList<TextDirective>;
create() { this.vc.createEmbeddedView(this.template); }
destroy() { this.vc.clear(); }
}