Whenever we want to create a new component using Angular CLI what we usually do is by running below command:
> ng generate component <component-name>
or in short
> ng g c <component-name>
So using this command Angular CLI generates below four files:
<component-name>.component.ts
<component-name>.component.html
<component-name>.component.css
<component-name>.component.spec.ts
But when we want to generate component with inline template and style we have to provide two options after the above command.
- For inline templates, we need to add --inlineTemplate=true. By default its value is false.
- For inline style, we need to add --inlineStyle=true. By default its value is false.
So final command looks like:
> ng generate component <component-name> --inlineTemplate=true --inlineStyle=true
For example if you generate component like
ng g c test --inlineTemplate=true --inlineStyle=true
This will generate a component file in which you can see below and it not generate separate template and css file:
test.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
template: `
<p>
test works!
</p>
`,
styles: []
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
Happy Coding!
You can follow me on twitter @sumitkharche01
Top comments (2)
Good write-up Sumit, I was using this approach for a while but I'm lazy so I started using the shorthand version of the options, -t=true -s=true, but that's still too much typing so I updated the defaults in my angular.json file.
"schematics": {
"@schematics/angular:component": {
"style": "scss",
"inlineTemplate": true,
"inlineStyle": true
}
},
Now when I run the following the component is generated in a single file with no additional components.
ng g c <component-name>
In Angular V.14, you should replace
inlineTemplate
withinline-template
andinlineStyle
with inline-styleto work with you and don't get this error:
Error: Unknown arguments: inlineTemplate, inlineStyle`. Thanks.