fix(core): static-query schematic should detect queries in "ngDoCheck" and "ngOnChanges" (#29492)

Queries can be also used statically within the "ngDoCheck" and "ngOnChanges" lifecylce hook.
In order to properly detect all queries, we need to also respect these lifecycle hooks.

Resolves FW-1192

PR Close #29492
This commit is contained in:
Paul Gschwendtner 2019-03-23 21:12:53 +01:00 committed by Misko Hevery
parent b3102b9de1
commit 09fab58109
2 changed files with 43 additions and 2 deletions

View File

@ -19,8 +19,9 @@ import {NgQueryDefinition, QueryTiming, QueryType} from './query-definition';
* could be used to access such a query statically. * could be used to access such a query statically.
*/ */
const STATIC_QUERY_LIFECYCLE_HOOKS = { const STATIC_QUERY_LIFECYCLE_HOOKS = {
[QueryType.ViewChild]: ['ngOnInit', 'ngAfterContentInit', 'ngAfterContentChecked'], [QueryType.ViewChild]:
[QueryType.ContentChild]: ['ngOnInit'], ['ngOnChanges', 'ngOnInit', 'ngDoCheck', 'ngAfterContentInit', 'ngAfterContentChecked'],
[QueryType.ContentChild]: ['ngOnChanges', 'ngOnInit', 'ngDoCheck'],
}; };
/** /**

View File

@ -161,6 +161,26 @@ describe('static-queries migration', () => {
.toContain(`@${queryType}('dynamic', { static: false }) dynamic: any`); .toContain(`@${queryType}('dynamic', { static: false }) dynamic: any`);
}); });
it('should mark queries used in "ngOnChanges" as static', () => {
writeFile('/index.ts', `
import {Component, ${queryType}} from '@angular/core';
@Component({template: '<span #test></span>'})
export class MyComp {
@${queryType}('test') query: any;
ngOnChanges() {
this.query.classList.add('test');
}
}
`);
runMigration();
expect(tree.readContent('/index.ts'))
.toContain(`@${queryType}('test', { static: true }) query: any;`);
});
it('should mark queries used in "ngOnInit" as static', () => { it('should mark queries used in "ngOnInit" as static', () => {
writeFile('/index.ts', ` writeFile('/index.ts', `
import {Component, ${queryType}} from '@angular/core'; import {Component, ${queryType}} from '@angular/core';
@ -181,6 +201,26 @@ describe('static-queries migration', () => {
.toContain(`@${queryType}('test', { static: true }) query: any;`); .toContain(`@${queryType}('test', { static: true }) query: any;`);
}); });
it('should mark queries used in "ngDoCheck" as static', () => {
writeFile('/index.ts', `
import {Component, ${queryType}} from '@angular/core';
@Component({template: '<span #test></span>'})
export class MyComp {
@${queryType}('test') query: any;
ngDoCheck() {
this.query.classList.add('test');
}
}
`);
runMigration();
expect(tree.readContent('/index.ts'))
.toContain(`@${queryType}('test', { static: true }) query: any;`);
});
it('should keep existing query options when updating timing', () => { it('should keep existing query options when updating timing', () => {
writeFile('/index.ts', ` writeFile('/index.ts', `
import {Component, ${queryType}} from '@angular/core'; import {Component, ${queryType}} from '@angular/core';