#4: ✏ A new component

In this chapter, we will write a whole new component. It will allow us to add an item to the todo list. It will be composed of the HTML elements input and button.

We'll use the Angular CLI to generate all the needed files and boilerplate for us. StackBlitz makes it easier. Go to the app folder and then select by right clicking the component option:

Name the component input and also make sure it has an inline-template.

Let's take a look at what the Angular CLI created for us.

It created a new folder called 📁 src/app/input. There are three files there:

input.component.ts
  template: `
    <p>
      input Works!
    </p>
  `,

It has also added the selector according to the name we gave to the component, with the prefix we configured:

input.component.ts
selector: 'todo-input',

We can use this component as-is and see the result!

app.component.ts
template: `
  <h1>
    Welcome to {{title}}!
  </h1>

  <todo-input></todo-input>
`,

Check what's new in the browser!

input.component.ts
export class InputComponent implements OnInit {
  title: string = '';
  ...

It will not interfere with the todo-root component's title, since each component's content is encapsulated within it.

You can give an initial string to the title, like we did in the todo-root component.

Next, replace the default template with an input element, a button, and a binding to the title:

input.component.ts
template: `
  <input>
  <button>Save</button>
  <p>The title is: {{ title }}</p>
`,

Check out the result!

This component doesn't do much at this point. In the following chapters, we will learn about the component class, and then implement the component's logic.

Last updated