Let's suppose I need an Angular component which is so small that the best option for it would be a single-file component.
An error alert like the one below would be such an example:
@Component({
selector: 'app-errors',
template: `<div class="alert-error">{{ errorMessage }}</div>`,
styles: [
`
.alert-error {
color: #721c24;
background-color: #f8d7da;
border-color: #f5c6cb;
padding: 0.75rem 1.25rem;
margin-bottom: 1rem;
text-align: center;
border: 1px solid transparent;
border-radius: 0.25rem;
}
`,
],
})
export class ErrorsComponent {}
In order to make this component I have run ng g c error-alert
in the CLI. Then I deleted all the files generated by the CLI except error-alert.ts
. Then I moved it outside of the error-alert directory (which I deleted).
I wished (and still do) there was a simpler and faster way to make a single-file component.
You could try adding some flags like so.
> ng generate component <component-name> --inlineTemplate=true --inlineStyle=true --skip-tests=true
This should stop the generation of css/html/spec file.
There is now also an option on more modern versions to do the same with standalone components.
--standalone
More options surrounding generating with specific goals can be found in the angular CLI docs.
You can also edit schematics
object in your angular.json
to set these flags to default when generating a component if you wanted to take this further.
"schematics": {
"@schematics/angular": {
"component": {
"inlineTemplate": true
}
}
}
You can add a new configuration to make ng g component
generate only one ts and spec file.
In angular.json
, add the following under "sematics" property:
"schematics": {
"@schematics/angular:component": {
"inlineStyle": true,
"inlineTemplate": true
}
}
Also, you can use extensions to get CSS and HTML syntax highlighting. Here is one - https://marketplace.visualstudio.com/items?itemName=Angular.ng-template
More in depth tutorial to creating single file component in Angular - https://muhimasri.com/blogs/how-to-create-a-single-file-component-in-angular/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With