Generate component with inline template and style using Angular CLI
Sumit Kharche

Sumit Kharche @sumitkharche

About: Full stack developer from Pune, India. C# Corner MVP

Location:
Pune
Joined:
Oct 13, 2018

Generate component with inline template and style using Angular CLI

Publish Date: Jan 5 '20
19 2

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>
Enter fullscreen mode Exit fullscreen mode

or in short

> ng g c <component-name>
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

But when we want to generate component with inline template and style we have to provide two options after the above command.

  1. For inline templates, we need to add --inlineTemplate=true. By default its value is false.
  2. 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
Enter fullscreen mode Exit fullscreen mode

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() {
  }

}

Enter fullscreen mode Exit fullscreen mode

Happy Coding!

You can follow me on twitter @sumitkharche01

Comments 2 total

  • Ashley Evans
    Ashley EvansMar 5, 2020

    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>

  • Ahmed Khairy
    Ahmed KhairyDec 28, 2022

    In Angular V.14, you should replace inlineTemplate with inline-template and inlineStyle with inline-styleto work with you and don't get this error:
    Error: Unknown arguments: inlineTemplate, inlineStyle`. Thanks.

Add comment