Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion packages/schematics/angular/application/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ export default function (options: ApplicationOptions): Rule {
const { appDir, appRootSelector, componentOptions, folderName, sourceDir } =
await getAppOptions(host, options);

const suffix = options.fileNameStyleGuide === '2016' ? '.component' : '';

return chain([
addAppToWorkspaceFile(options, appDir),
addTsProjectReference('./' + join(normalize(appDir), 'tsconfig.app.json')),
Expand Down Expand Up @@ -108,6 +110,7 @@ export default function (options: ApplicationOptions): Rule {
relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(appDir),
appName: options.name,
folderName,
suffix,
}),
move(appDir),
]),
Expand All @@ -119,7 +122,7 @@ export default function (options: ApplicationOptions): Rule {
? filter((path) => !path.endsWith('tsconfig.spec.json.template'))
: noop(),
componentOptions.inlineTemplate
? filter((path) => !path.endsWith('app.html.template'))
? filter((path) => !path.endsWith('app__suffix__.html.template'))
: noop(),
applyTemplates({
utils: strings,
Expand All @@ -128,6 +131,7 @@ export default function (options: ApplicationOptions): Rule {
relativePathToWorkspaceRoot: relativePathToWorkspaceRoot(appDir),
appName: options.name,
folderName,
suffix,
}),
move(appDir),
]),
Expand Down Expand Up @@ -233,6 +237,20 @@ function addAppToWorkspaceFile(options: ApplicationOptions, appDir: string): Rul
});
}

if (options.fileNameStyleGuide === '2016') {
const schematicsWithTypeSymbols = ['component', 'directive', 'service'];
schematicsWithTypeSymbols.forEach((type) => {
const schematicDefaults = (schematics[`@schematics/angular:${type}`] ??= {}) as JsonObject;
schematicDefaults.type = type;
schematicDefaults.addTypeToClassName = false;
});

const schematicsWithTypeSeparator = ['guard', 'interceptor', 'module', 'pipe', 'resolver'];
schematicsWithTypeSeparator.forEach((type) => {
((schematics[`@schematics/angular:${type}`] ??= {}) as JsonObject).typeSeparator = '.';
});
}

const sourceRoot = join(normalize(projectRoot), 'src');
let budgets: { type: string; maximumWarning: string; maximumError: string }[] = [];
if (options.strict) {
Expand Down Expand Up @@ -389,5 +407,10 @@ function getComponentOptions(options: ApplicationOptions): Partial<ComponentOpti
viewEncapsulation: options.viewEncapsulation,
};

if (options.fileNameStyleGuide === '2016') {
componentOptions.type = 'component';
componentOptions.addTypeToClassName = false;
}

return componentOptions;
}
6 changes: 6 additions & 0 deletions packages/schematics/angular/application/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,12 @@
"x-prompt": "Do you want to create a 'zoneless' application without zone.js?",
"type": "boolean",
"default": false
},
"fileNameStyleGuide": {
"type": "string",
"enum": ["2016", "2025"],
"default": "2025",
"description": "The file naming convention to use for generated files. The '2025' style guide (default) uses a concise format (e.g., `app.ts` for the root component), while the '2016' style guide includes the type in the file name (e.g., `app.component.ts`). For more information, see the Angular Style Guide (https://angular.dev/style-guide)."
}
},
"required": ["name"]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import <% if(!exportDefault) { %>{ <% }%><%= classify(name) %><%= classify(type) %> <% if(!exportDefault) {%>} <% }%>from './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>';
import <% if(!exportDefault) { %>{ <% }%><%= classifiedName %> <% if(!exportDefault) {%>} <% }%>from './<%= dasherize(name) %><%= type ? '.' + dasherize(type): '' %>';

describe('<%= classify(name) %><%= classify(type) %>', () => {
let component: <%= classify(name) %><%= classify(type) %>;
let fixture: ComponentFixture<<%= classify(name) %><%= classify(type) %>>;
describe('<%= classifiedName %>', () => {
let component: <%= classifiedName %>;
let fixture: ComponentFixture<<%= classifiedName %>>;

beforeEach(async () => {
await TestBed.configureTestingModule({
<%= standalone ? 'imports' : 'declarations' %>: [<%= classify(name) %><%= classify(type) %>]
<%= standalone ? 'imports' : 'declarations' %>: [<%= classifiedName %>]
})
.compileComponents();

fixture = TestBed.createComponent(<%= classify(name) %><%= classify(type) %>);
fixture = TestBed.createComponent(<%= classifiedName %>);
component = fixture.componentInstance;
fixture.detectChanges();
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ import { <% if(changeDetection !== 'Default') { %>ChangeDetectionStrategy, <% }%
encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>,
changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %>
})
export <% if(exportDefault) {%>default <%}%>class <%= classify(name) %><%= classify(type) %> {
export <% if(exportDefault) {%>default <%}%>class <%= classifiedName %> {

}
8 changes: 7 additions & 1 deletion packages/schematics/angular/component/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,11 @@ export default createProjectSchematic<ComponentOptions>((options, { project, tre
options.selector = options.selector || buildSelector(options, (project && project.prefix) || '');

validateHtmlSelector(options.selector);
validateClassName(strings.classify(options.name));

const classifiedName =
strings.classify(options.name) +
(options.addTypeToClassName && options.type ? strings.classify(options.type) : '');
validateClassName(classifiedName);

const skipStyleFile = options.inlineStyle || options.style === Style.None;
const templateSource = apply(url('./files'), [
Expand All @@ -66,6 +70,8 @@ export default createProjectSchematic<ComponentOptions>((options, { project, tre
'if-flat': (s: string) => (options.flat ? '' : s),
'ngext': options.ngHtml ? '.ng' : '',
...options,
// Add a new variable for the classified name, conditionally including the type
classifiedName,
}),
!options.type
? forEach(((file) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/schematics/angular/component/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ describe('Component Schematic', () => {

await expectAsync(
schematicRunner.runSchematic('component', options, appTree),
).toBeRejectedWithError('Class name "404" is invalid.');
).toBeRejectedWithError('Class name "404Component" is invalid.');
});

it('should allow dash in selector before a number', async () => {
Expand Down
5 changes: 5 additions & 0 deletions packages/schematics/angular/component/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@
"type": "string",
"description": "Append a custom type to the component's filename. For example, if you set the type to `container`, the file will be named `my-component.container.ts`."
},
"addTypeToClassName": {
"type": "boolean",
"default": true,
"description": "When true, the 'type' option will be appended to the generated class name. When false, only the file name will include the type."
},
"skipTests": {
"type": "boolean",
"description": "Skip the generation of unit test files `spec.ts`.",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { <%= classify(name) %><%= classify(type) %> } from './<%= dasherize(name) %><%= type ? '.' + dasherize(type) : '' %>';
import { <%= classifiedName %> } from './<%= dasherize(name) %><%= type ? '.' + dasherize(type) : '' %>';

describe('<%= classify(name) %><%= classify(type) %>', () => {
describe('<%= classifiedName %>', () => {
it('should create an instance', () => {
const directive = new <%= classify(name) %><%= classify(type) %>();
const directive = new <%= classifiedName %>();
expect(directive).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Directive } from '@angular/core';
selector: '[<%= selector %>]'<% if(!standalone) {%>,
standalone: false<%}%>
})
export class <%= classify(name) %><%= classify(type) %> {
export class <%= classifiedName %> {

constructor() { }

Expand Down
10 changes: 8 additions & 2 deletions packages/schematics/angular/directive/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,20 @@ export default createProjectSchematic<DirectiveOptions>((options, { project, tre
options.selector = options.selector || buildSelector(options, project.prefix || '');

validateHtmlSelector(options.selector);
validateClassName(strings.classify(options.name));
const classifiedName =
strings.classify(options.name) +
(options.addTypeToClassName && options.type ? strings.classify(options.type) : '');
validateClassName(classifiedName);

return chain([
addDeclarationToNgModule({
type: 'directive',

...options,
}),
generateFromFiles(options),
generateFromFiles({
...options,
classifiedName,
}),
]);
});
29 changes: 29 additions & 0 deletions packages/schematics/angular/directive/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,35 @@ describe('Directive Schematic', () => {
expect(testContent).toContain("describe('Foo'");
});

it('should not add type to class name when addTypeToClassName is false', async () => {
const options = { ...defaultOptions, type: 'Directive', addTypeToClassName: false };
const tree = await schematicRunner.runSchematic('directive', options, appTree);
const content = tree.readContent('/projects/bar/src/app/foo.directive.ts');
const testContent = tree.readContent('/projects/bar/src/app/foo.directive.spec.ts');
expect(content).toContain('export class Foo {');
expect(content).not.toContain('export class FooDirective {');
expect(testContent).toContain("describe('Foo', () => {");
expect(testContent).not.toContain("describe('FooDirective', () => {");
});

it('should add type to class name when addTypeToClassName is true', async () => {
const options = { ...defaultOptions, type: 'Directive', addTypeToClassName: true };
const tree = await schematicRunner.runSchematic('directive', options, appTree);
const content = tree.readContent('/projects/bar/src/app/foo.directive.ts');
const testContent = tree.readContent('/projects/bar/src/app/foo.directive.spec.ts');
expect(content).toContain('export class FooDirective {');
expect(testContent).toContain("describe('FooDirective', () => {");
});

it('should add type to class name by default', async () => {
const options = { ...defaultOptions, type: 'Directive', addTypeToClassName: undefined };
const tree = await schematicRunner.runSchematic('directive', options, appTree);
const content = tree.readContent('/projects/bar/src/app/foo.directive.ts');
const testContent = tree.readContent('/projects/bar/src/app/foo.directive.spec.ts');
expect(content).toContain('export class FooDirective {');
expect(testContent).toContain("describe('FooDirective', () => {");
});

describe('standalone=false', () => {
const defaultNonStandaloneOptions: DirectiveOptions = {
...defaultOptions,
Expand Down
5 changes: 5 additions & 0 deletions packages/schematics/angular/directive/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@
"type": {
"type": "string",
"description": "Append a custom type to the directive's filename. For example, if you set the type to `directive`, the file will be named `example.directive.ts`."
},
"addTypeToClassName": {
"type": "boolean",
"default": true,
"description": "When true, the 'type' option will be appended to the generated class name. When false, only the file name will include the type."
}
},
"required": ["name", "project"]
Expand Down
1 change: 1 addition & 0 deletions packages/schematics/angular/ng-new/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export default function (options: NgNewOptions): Rule {
standalone: options.standalone,
ssr: options.ssr,
zoneless: options.zoneless,
fileNameStyleGuide: options.fileNameStyleGuide,
};

return chain([
Expand Down
38 changes: 38 additions & 0 deletions packages/schematics/angular/ng-new/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,42 @@ describe('Ng New Schematic', () => {
const stylesContent = tree.readContent('/bar/src/styles.css');
expect(stylesContent).toContain('@import "tailwindcss";');
});

it(`should create files with file name style guide '2016'`, async () => {
const options = { ...defaultOptions, fileNameStyleGuide: '2016' };

const tree = await schematicRunner.runSchematic('ng-new', options);
const files = tree.files;
expect(files).toEqual(
jasmine.arrayContaining([
'/bar/src/app/app.component.css',
'/bar/src/app/app.component.html',
'/bar/src/app/app.component.spec.ts',
'/bar/src/app/app.component.ts',
]),
);

const {
projects: {
'foo': { schematics },
},
} = JSON.parse(tree.readContent('/bar/angular.json'));
expect(schematics['@schematics/angular:component'].type).toBe('component');
expect(schematics['@schematics/angular:directive'].type).toBe('directive');
expect(schematics['@schematics/angular:service'].type).toBe('service');
expect(schematics['@schematics/angular:guard'].typeSeparator).toBe('.');
expect(schematics['@schematics/angular:interceptor'].typeSeparator).toBe('.');
expect(schematics['@schematics/angular:module'].typeSeparator).toBe('.');
expect(schematics['@schematics/angular:pipe'].typeSeparator).toBe('.');
expect(schematics['@schematics/angular:resolver'].typeSeparator).toBe('.');
});

it(`should not add type to class name when file name style guide is '2016'`, async () => {
const options = { ...defaultOptions, fileNameStyleGuide: '2016' };

const tree = await schematicRunner.runSchematic('ng-new', options);
const appComponentContent = tree.readContent('/bar/src/app/app.component.ts');
expect(appComponentContent).toContain('export class App {');
expect(appComponentContent).not.toContain('export class AppComponent {');
});
});
6 changes: 6 additions & 0 deletions packages/schematics/angular/ng-new/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,12 @@
"type": "string",
"enum": ["none", "gemini", "copilot", "claude", "cursor", "jetbrains", "windsurf"]
}
},
"fileNameStyleGuide": {
"type": "string",
"enum": ["2016", "2025"],
"default": "2025",
"description": "The file naming convention to use for generated files. The '2025' style guide (default) uses a concise format (e.g., `app.ts` for the root component), while the '2016' style guide includes the type in the file name (e.g., `app.component.ts`). For more information, see the Angular Style Guide (https://angular.dev/style-guide)."
}
},
"required": ["name", "version"]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { TestBed } from '@angular/core/testing';

import { <%= classify(name) %><%= classify(type) %> } from './<%= dasherize(name) %><%= type ? '.' + dasherize(type) : '' %>';
import { <%= classifiedName %> } from './<%= dasherize(name) %><%= type ? '.' + dasherize(type) : '' %>';

describe('<%= classify(name) %><%= classify(type) %>', () => {
let service: <%= classify(name) %><%= classify(type) %>;
describe('<%= classifiedName %>', () => {
let service: <%= classifiedName %>;

beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(<%= classify(name) %><%= classify(type) %>);
service = TestBed.inject(<%= classifiedName %>);
});

it('should be created', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class <%= classify(name) %><%= classify(type) %> {
export class <%= classifiedName %> {

}
28 changes: 24 additions & 4 deletions packages/schematics/angular/service/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,30 @@
* found in the LICENSE file at https://angular.dev/license
*/

import { Rule } from '@angular-devkit/schematics';
import { Rule, strings } from '@angular-devkit/schematics';
import { generateFromFiles } from '../utility/generate-from-files';
import { parseName } from '../utility/parse-name';
import { createProjectSchematic } from '../utility/project';
import { validateClassName } from '../utility/validation';
import { buildDefaultPath } from '../utility/workspace';
import { Schema as ServiceOptions } from './schema';

export default function (options: ServiceOptions): Rule {
return generateFromFiles(options);
}
export default createProjectSchematic<ServiceOptions>((options, { project, tree }) => {
if (options.path === undefined) {
options.path = buildDefaultPath(project);
}

const parsedPath = parseName(options.path, options.name);
options.name = parsedPath.name;
options.path = parsedPath.path;

const classifiedName =
strings.classify(options.name) +
(options.addTypeToClassName && options.type ? strings.classify(options.type) : '');
validateClassName(classifiedName);

return generateFromFiles({
...options,
classifiedName,
});
});
Loading