feat(angular): add helper function to devkit to add viewProviders to a component (#26526)

## Current Behavior

Angular Nx utils have `addProviderToComponent` function to add a
provider to an Angular component, but are missing a function to add
viewProviders.

## Expected Behavior

There should be a function like `addProviderToComponent` to add view
providers to a component.

Co-authored-by: Leosvel Pérez Espinosa <leosvel.perez.espinosa@gmail.com>
This commit is contained in:
Pavlo Grosse 2024-06-17 10:51:49 +02:00 committed by GitHub
parent f431d0a6a1
commit 15b7e9f079
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 71 additions and 0 deletions

View File

@ -14,6 +14,7 @@ export {
addProviderToAppConfig,
addProviderToComponent,
addProviderToModule,
addViewProviderToComponent,
} from './nx-devkit/ast-utils';
export { addRoute, addProviderToRoute } from './nx-devkit/route-utils';

View File

@ -5,6 +5,7 @@ import {
addImportToPipe,
addProviderToAppConfig,
addProviderToBootstrapApplication,
addViewProviderToComponent,
isStandalone,
} from './ast-utils';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
@ -334,4 +335,50 @@ export const appConfig: ApplicationConfig = {
};"
`);
});
it('should add view provider to a component', () => {
// ARRANGE
const pathToComponent = 'app.component.ts';
const componentOriginal = `import { Component } from '@angular/core';
@Component({
selector: 'app-app',
template: ''
})
export class AppComponent {}
`;
const providerName = 'MyViewProvider';
const tree = createTreeWithEmptyWorkspace({ layout: 'apps-libs' });
tree.write(pathToComponent, componentOriginal);
const tsSourceFile = createSourceFile(
pathToComponent,
componentOriginal,
ScriptTarget.Latest,
true
);
// ACT
addViewProviderToComponent(
tree,
tsSourceFile,
pathToComponent,
providerName
);
// ASSERT
expect(tree.read(pathToComponent, 'utf-8')).toMatchInlineSnapshot(`
"import { Component } from '@angular/core';
@Component({
selector: 'app-app',
template: '',
viewProviders: [MyViewProvider]
})
export class AppComponent {}
"
`);
});
});

View File

@ -826,6 +826,29 @@ export function addProviderToComponent(
);
}
/**
* Add a view provider to a Standalone Component
* @param host Virtual Tree
* @param source TS Source File containing the Component
* @param componentPath Path to the Component
* @param symbolName The provider to add
*/
export function addViewProviderToComponent(
host: Tree,
source: ts.SourceFile,
componentPath: string,
symbolName: string
): ts.SourceFile {
return _addSymbolToDecoratorMetadata(
host,
source,
componentPath,
'viewProviders',
symbolName,
'Component'
);
}
export function addDeclarationToModule(
host: Tree,
source: ts.SourceFile,