Blog

Part 5 · Component Inputs in Angular: input(), required and transform

A page gets easier to read when it’s split into small components, and inputs are how a parent hands each one its data. This part covers input(), required inputs, transforms, aliases and a product list.

So far every page has lived in one component, App. That’s fine for a counter. A real page has a header, a list, a card for each item, a footer. If all of that sits in one template, it gets long and hard to change. So we split the page into smaller components, each in its own file, and put them together in App.

A child component on its own shows the same thing every time. To show a different product in each card, the parent has to hand data down to it. That’s what an input is. This part covers input(), required inputs, the difference between a static string and a bound expression, transform, alias, and why an input is a signal you can read but can’t set. It builds on signals from Part 3 and @for from Part 4. Every example here is a whole file you can paste into your practice project from Part 1. Each one was built with Angular 22.3 and run in a browser before this was published.

Try this first

This example has two files. Make a new file src/app/product-card.ts and paste the first one. Paste the second into src/app/app.ts.

// src/app/product-card.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>Product: {{ name() }}</p>`,
})
export class ProductCard {
  readonly name = input('Unnamed');
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `
    <app-product-card />
    <app-product-card name="Tea" />
    <app-product-card [name]="favourite()" />
    <button (click)="favourite.set('Cocoa')">Change favourite</button>
  `,
})
export class App {
  protected readonly favourite = signal('Coffee');
}

Before you read on, guess. The page has three cards. What does each one say? Then you click Change favourite. Which cards change?

Here’s what happens. When the page loads, it shows:

Product: Unnamed
Product: Tea
Product: Coffee
Change favourite

Click Change favourite, and the page shows:

Product: Unnamed
Product: Tea
Product: Cocoa
Change favourite

The first card got nothing, so it used its default. The second got the fixed text Tea. The third got the value of the parent’s favourite signal, and it followed that signal when it changed. The rest of this part explains each of those three lines.

A component inside a component

ProductCard is a component like App. It has a selector, app-product-card, and a template. In Part 1 we used a second component by importing its class and listing it in imports: []. App does that here, and then its template can use <app-product-card /> as many times as it likes. Each use makes a new, separate ProductCard.

We call App the parent and each card a child. The parent’s template contains the child’s tag. The child knows nothing about the parent. It only knows what the parent hands it.

The /> at the end of <app-product-card /> closes the tag in one go. Angular allows that for component tags. <app-product-card></app-product-card> means the same.

input(): a value the parent hands in

This line in ProductCard declares the input:

readonly name = input('Unnamed');

input() comes from @angular/core. The value in the brackets is the default: what the card uses when the parent doesn’t pass anything. TypeScript works out the type from it, as signal() did in Part 3. input('Unnamed') is an input of strings.

An input is a signal. Inside the child you read it by calling it: name() in the template, this.name() in the class. When the parent passes a new value, the signal changes, and anything that read it is redrawn. That’s why the third card switched to Cocoa.

The field is readonly, like our signals in Part 3. It isn’t protected, because the parent’s template uses it too: name is part of what the card offers to the outside.

A static string or a bound expression

The parent passed name in two ways:

  • name="Tea" looks like a normal HTML attribute. The value is the text between the quotes, always a string, and it never changes.
  • [name]="favourite()" is a property binding, the square brackets from Part 2. Angular runs the expression favourite() and passes the result. When favourite changes, Angular runs it again and passes the new value.

For a string, both work. For anything else, the difference matters. Here the card gets a price, with a default of 0:

// src/app/product-card.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>{{ name() }}: {{ price() }}</p>`,
})
export class ProductCard {
  readonly name = input('Unnamed');
  readonly price = input(0);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `<app-product-card name="Tea" price="5" />`,
})
export class App {}

It looks right. ng serve won’t build it:

✘ [ERROR] TS2322: Type 'string' is not assignable to type 'number'. [plugin angular-compiler]
      8 │   template: `<app-product-card name="Tea" price="5" />`,

Read it piece by piece:

  • TS2322 is the TypeScript code for “this value doesn’t fit this type”.
  • Type 'string' is not assignable to type 'number' says what went wrong. price="5" passes the text "5", a string. price is an input of numbers, because its default is 0.
  • The line under it, with ~~~~~ in the real output, points at price in the template. The error is in app.ts, the parent, not in the card. The parent passed the wrong thing.

A new Angular project has strict template checking on. You won’t find strictTemplates written in tsconfig.json: in Angular 22 the compiler treats it as on unless a project turns it off. Angular checks every binding in a template against the input’s type, the same way TypeScript checks a function call. That’s how it caught this before the page ever ran.

The fix is a binding. [price]="5" runs 5 as an expression, and the expression 5 is the number 5:

// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `<app-product-card name="Tea" [price]="5" />`,
})
export class App {}

The page shows:

Tea: 5

The rule: no brackets passes the text; brackets pass the result of an expression. Use brackets for numbers, booleans, objects, and anything that comes from a signal.

Required inputs

A default makes sense for some inputs. For others it doesn’t. A product card with no name is a bug, and showing “Unnamed” only hides it. For those, use input.required:

// src/app/product-card.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>{{ name() }}: {{ price() }}</p>`,
})
export class ProductCard {
  readonly name = input.required<string>();
  readonly price = input.required<number>();
}
// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `<app-product-card name="Tea" />`,
})
export class App {}

A required input has no default, so TypeScript can’t work out its type. You give it in angle brackets, as a generic: input.required<string>() is a required input of strings. We met generics with signal<CartItem[]>([]) in Part 3.

The parent above forgot price. The build stops:

✘ [ERROR] NG8008: Required input 'price' from component ProductCard must be specified. [plugin angular-compiler]
      8 │   template: `<app-product-card name="Tea" />`,

Build errors that start with NG come from Angular’s compiler, not from TypeScript. (Codes like NG0955 in Part 4 come from Angular at runtime.) NG8008 names the input (price) and the component (ProductCard), and the line points at the tag that’s missing it. Add [price]="4" and it builds.

Required inputs move a mistake from “a card that looks a bit wrong” to “a build that names the problem”. Use them for anything the child can’t work without.

computed() from inputs

Inputs are signals, so computed() from Part 3 works with them. The card can work out its label from its name and price:

// src/app/product-card.ts
import { Component, computed, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>{{ label() }}</p>`,
})
export class ProductCard {
  readonly name = input.required<string>();
  readonly price = input.required<number>();

  protected readonly label = computed(() => `${this.name()}: $${this.price()}`);
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `
    <app-product-card name="Tea" [price]="teaPrice()" />
    <button (click)="raise()">Raise price</button>
  `,
})
export class App {
  protected readonly teaPrice = signal(4);

  protected raise() {
    this.teaPrice.update((p) => p + 1);
  }
}

In the template string, $${...} is a dollar sign followed by a ${...} placeholder. label is protected, because only the card’s own template uses it.

Click Raise price twice. The page shows:

Tea: $6
Raise price

The parent changed its own signal. The binding passed the new number down. The card’s price input changed, so label worked itself out again. Nobody told the card to update its label.

Inputs are read-only

What if the card wants to change its own price? Say it has a button that drops the price to 0:

// src/app/product-card.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `
    <p>{{ name() }}: {{ price() }}</p>
    <button (click)="makeFree()">Make free</button>
  `,
})
export class ProductCard {
  readonly name = input.required<string>();
  readonly price = input.required<number>();

  protected makeFree() {
    this.price.set(0);
  }
}
// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `<app-product-card name="Tea" [price]="4" />`,
})
export class App {}

The build says no:

✘ [ERROR] TS2339: Property 'set' does not exist on type 'InputSignal<number>'. [plugin angular-compiler]
      16 │     this.price.set(0);

This is the same TS2339 we met in Part 3 when we called set on a computed. input() returns an InputSignal. You can read it, but it has no set or update.

That’s on purpose. The price belongs to the parent. If the card could change it, the parent would hold one price and the card would show another, and nothing would say which was right. So data goes one way: down, from parent to child. The parent changes its own signal, and the new value flows down through the binding.

When a child needs the parent to change something, it asks: it sends an event up, and the parent decides. That’s an output, and Part 6 covers it.

Data flowing down the tree

Here’s the shape of the product list we’ll build in a moment. App holds the list in a signal. A @for makes one ProductCard per product, and binds each card’s inputs. Each card works out its own label.

App products = signal([…]) Tea $4 · Bread $3, on sale · Milk $2 @for (p of products(); track p.name) [name] [price] [onSale] [name] [price] [onSale] [name] [price] [onSale] ProductCard Tea: $4 label = computed(…) ProductCard Bread: $3 (on sale) label = computed(…) ProductCard Milk: $2 label = computed(…) Each card reads name(), price() and onSale(). It can't set them.

The parent owns the data. Each card’s [name], [price] and [onSale] are bound to p.name, p.price and p.onSale.

When the parent’s signal changes, the bindings run again, and only the cards whose inputs got a new value redraw.

transform: booleanAttribute and numberAttribute

Some inputs read best as plain HTML attributes. HTML has <input disabled>: the attribute is there or it isn’t. We’d like <app-product-card onSale /> to mean “on sale”. Try it with a plain boolean input:

// src/app/product-card.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>{{ name() }} {{ onSale() }}</p>`,
})
export class ProductCard {
  readonly name = input.required<string>();
  readonly onSale = input(false);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `<app-product-card name="Bread" onSale />`,
})
export class App {}
✘ [ERROR] TS2322: Type 'string' is not assignable to type 'boolean'. [plugin angular-compiler]

It’s the same mistake as price="5". An attribute with no value passes the empty string "", and onSale wants a boolean. You could write [onSale]="true". Or you can tell the input how to turn the string into a boolean, with a transform:

// src/app/product-card.ts
import { booleanAttribute, Component, input, numberAttribute } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>{{ name() }}: {{ price() }}, on sale: {{ onSale() }}</p>`,
})
export class ProductCard {
  readonly name = input.required<string>();
  readonly price = input(0, { transform: numberAttribute });
  readonly onSale = input(false, { transform: booleanAttribute });
}
// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `
    <app-product-card name="Tea" price="4" />
    <app-product-card name="Bread" price="3" onSale />
    <app-product-card name="Milk" price="two" [onSale]="false" />
  `,
})
export class App {}

The page shows:

Tea: 4, on sale: false
Bread: 3, on sale: true
Milk: NaN, on sale: false

A transform is a function that Angular runs on every value the parent passes, before the input stores it. The second argument to input() is an options object, and transform is one of its options. Angular ships two transforms:

  • booleanAttribute turns the attribute being present (onSale, onSale="") into true. It passes real booleans through, so [onSale]="false" still works. Only the text "false", null and undefined give false. Every other value gives true, including "no" and "0".
  • numberAttribute turns "4" into the number 4 and passes real numbers through. Text that isn’t a number becomes NaN, JavaScript’s “not a number”. That’s what the Milk card shows. An empty price="" gives NaN too, not 0.

There’s a cost. booleanAttribute and numberAttribute take a value of type unknown, so an input with a transform accepts any value, even a bound one. Strict checking can’t catch a mistake there. This builds without a word:

// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `
    <app-product-card name="Tea" price="" onSale="no" />
    <app-product-card name="Milk" [price]="label" [onSale]="0" />
  `,
})
export class App {
  protected readonly label = 'Milk';
}

The page shows:

Tea: NaN, on sale: true
Milk: NaN, on sale: true

A string bound to [price] gives NaN, and onSale="no" and [onSale]="0" both mean on sale.

So use numberAttribute with care. For a price that comes from data, [price]="p.price" with a plain number input is safer. booleanAttribute is the one you’ll use most, for flags like disabled, compact or onSale.

You can write your own transform too: any function that takes the passed value and returns the stored one.

alias: a different name outside

Sometimes the name the parent writes and the name the class uses should differ. alias sets the outside name:

// src/app/product-card.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>{{ name() }}</p>`,
})
export class ProductCard {
  readonly name = input.required<string>({ alias: 'productName' });
}
// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `<app-product-card productName="Tea" />`,
})
export class App {}

The page shows:

Tea

The parent writes productName. The class reads name(). You’ll mostly see aliases where a component library wants a prefix on its public names, or where a renamed input has to keep its old name for the code that uses it. In your own components, pick a good name and skip the alias. Two names for one thing is one more thing to keep in your head.

Passing objects: don’t change them in place

An input can be any type, including an object. That’s handy when a card needs many fields. But the rule from Part 3 comes back. A signal decides whether something changed by comparing references: is it the same object, not does it hold the same values. Inputs do the same.

Here the parent raises the price by changing the object it already has:

// src/app/product-card.ts
import { Component, input } from '@angular/core';

export interface Product {
  name: string;
  price: number;
}

@Component({
  selector: 'app-product-card',
  template: `<p>{{ product().name }}: {{ product().price }}</p>`,
})
export class ProductCard {
  readonly product = input.required<Product>();
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Product, ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `
    <app-product-card [product]="tea()" />
    <p>Parent says: {{ tea().price }}</p>
    <button (click)="raise()">Raise price</button>
  `,
})
export class App {
  protected readonly tea = signal<Product>({ name: 'Tea', price: 4 });

  protected raise() {
    this.tea.update((p) => {
      p.price++;
      return p;
    });
  }
}

export interface Product lets app.ts import the type from the card’s file. An interface only describes a shape, so it isn’t listed in imports: [].

Click Raise price. The page shows:

Tea: 4
Parent says: 5
Raise price

The parent and the child disagree. The click redrew App, so its own text shows 5. But tea() is the same object as before, so the card’s input didn’t change, and the card wasn’t redrawn. It still shows 4. In a new Angular 22 project, a child is redrawn when one of its inputs gets a new value, when a signal its template reads changes, or when an event happens inside it. None of those happened here. The tea signal didn’t notify anyone either, because it holds the same object. Only the click made App redraw.

The fix is the one from Part 3: make a new object. { ...p, price: p.price + 1 } copies every field of p into a new object, then sets price:

// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Product, ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `
    <app-product-card [product]="tea()" />
    <p>Parent says: {{ tea().price }}</p>
    <button (click)="raise()">Raise price</button>
  `,
})
export class App {
  protected readonly tea = signal<Product>({ name: 'Tea', price: 4 });

  protected raise() {
    this.tea.update((p) => ({ ...p, price: p.price + 1 }));
  }
}

Click Raise price, and the page shows:

Tea: 5
Parent says: 5
Raise price

Treat anything you pass as an input as frozen. The parent replaces it; nobody changes it.

Worked example: a product list

Now we’ll put it together. App keeps the products in a signal and draws one ProductCard per product with @for. Each card has two required inputs and a boolean flag, and works out its label with computed. A button puts the milk on sale.

// src/app/product-card.ts
import { booleanAttribute, Component, computed, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>{{ label() }}</p>`,
})
export class ProductCard {
  readonly name = input.required<string>();
  readonly price = input.required<number>();
  readonly onSale = input(false, { transform: booleanAttribute });

  protected readonly label = computed(() => {
    const text = `${this.name()}: $${this.price()}`;
    return this.onSale() ? `${text} (on sale)` : text;
  });
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { ProductCard } from './product-card';

interface Product {
  name: string;
  price: number;
  onSale: boolean;
}

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `
    @for (p of products(); track p.name) {
      <app-product-card [name]="p.name" [price]="p.price" [onSale]="p.onSale" />
    }
    <app-product-card name="Gift card" [price]="10" onSale />
    <button (click)="milkOnSale()">Put milk on sale</button>
  `,
})
export class App {
  protected readonly products = signal<Product[]>([
    { name: 'Tea', price: 4, onSale: false },
    { name: 'Bread', price: 3, onSale: true },
    { name: 'Milk', price: 2, onSale: false },
  ]);

  protected milkOnSale() {
    this.products.update((list) =>
      list.map((p) => (p.name === 'Milk' ? { ...p, onSale: true } : p)),
    );
  }
}

Some things to notice:

  • Inside @for, every input is a binding: [name]="p.name" and so on. The values come from data, so they need brackets.
  • The gift card outside the loop uses the other styles: a static name, a bound number, and the bare onSale attribute. booleanAttribute accepts both onSale and [onSale]="p.onSale". Because onSale has a transform, the build doesn’t check that p.onSale is a boolean. Our Product interface does that job instead.
  • track p.name tells @for which card is which, as in Part 4. When the list changes, Angular keeps the cards it already has and updates their inputs.
  • milkOnSale uses map, which returns a new list. The milk gets a new object; Tea and Bread keep theirs.

The page shows:

Tea: $4
Bread: $3 (on sale)
Milk: $2
Gift card: $10 (on sale)
Put milk on sale

Click Put milk on sale. The page shows:

Tea: $4
Bread: $3 (on sale)
Milk: $2 (on sale)
Gift card: $10 (on sale)
Put milk on sale

Only the milk’s onSale input got a new value, so only the milk’s label was worked out again. (We checked with a console.log inside label: after the click it logged once, for Milk.) Tea and Bread got the same values as before, and the gift card’s bindings didn’t change at all.

Worked example: two errors in one build

A teammate adds a stock count to the card. stock is a new required input. Then they update the parent, but type stok by mistake:

// src/app/product-card.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-product-card',
  template: `<p>{{ name() }}: {{ stock() }} left</p>`,
})
export class ProductCard {
  readonly name = input.required<string>();
  readonly stock = input.required<number>();
}
// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `<app-product-card name="Tea" [stok]="3" />`,
})
export class App {}

ng serve prints two errors:

✘ [ERROR] NG8002: Can't bind to 'stok' since it isn't a known property of 'app-product-card'.
1. If 'app-product-card' is an Angular component and it has 'stok' input, then verify that it is included in the '@Component.imports' of this component.
      8 │   template: `<app-product-card name="Tea" [stok]="3" />`,
✘ [ERROR] NG8008: Required input 'stock' from component ProductCard must be specified. [plugin angular-compiler]

Read them in order, but think about them together:

  • NG8002 says [stok] isn’t a known property of app-product-card. Angular looked for an input called stok on ProductCard, then for a normal DOM property, and found neither. Its first hint is about a missing imports entry, because that’s the most common cause: if you forget to import a component, none of its inputs are known. Here the import is fine. The name is wrong.
  • NG8008 says the required input stock is missing. That’s the same typo, seen from the other side. The parent did try to pass the stock. It used the wrong name.

When two errors point at the same tag, fix the first and build again before you chase the second. Here one fix clears both:

// src/app/app.ts
import { Component } from '@angular/core';
import { ProductCard } from './product-card';

@Component({
  selector: 'app-root',
  imports: [ProductCard],
  template: `<app-product-card name="Tea" [stock]="3" />`,
})
export class App {}

The page shows:

Tea: 3 left

In older code

Before input(), an input was a class field with the @Input() decorator: @Input() name = 'Unnamed';, or @Input({ required: true }) name!: string;. It was a plain field, not a signal, so you read it without (), and the child could assign to it. To react when an input changed, a component implemented ngOnChanges(changes: SimpleChanges), a method Angular called with the old and new values. With input(), a computed does that job. You’ll meet @Input() and ngOnChanges in many existing projects. They still work, but new code uses input().

Best practices

  • Use input.required<T>() for anything the child can’t work without. A missing value becomes NG8008 at build time instead of a card that quietly shows a default. It replaces defaults like 'Unnamed' that hide bugs.
  • Bind with brackets for anything that isn’t fixed text. [price]="5", [onSale]="p.onSale". Strict template checking then catches type mistakes. Inputs with a transform are the exception: they accept any value, so the binding isn’t checked. It replaces passing strings and converting them by hand.
  • Work out display values with computed from inputs. The label follows the inputs and is cached. It replaces ngOnChanges and fields you update by hand.
  • Use booleanAttribute for on/off flags. <app-product-card onSale /> reads like HTML. It replaces [onSale]="true" everywhere.
  • Treat inputs as read-only data owned by the parent. Pass new objects, never change one in place, and let the parent change its own signal. Part 6 shows how the child asks it to.
  • Mark inputs readonly, and leave them public. The parent’s template binds to them; protected is for things only the child’s template uses, like label.

Tips and traps

  • price="5" on a number input. The build fails with TS2322, Type 'string' is not assignable to type 'number', pointing at the parent’s template. Write [price]="5".
  • A bare flag without a transform. <app-product-card onSale /> on input(false) fails with TS2322 for boolean. Add transform: booleanAttribute, or bind [onSale]="true".
  • Calling set on an input. TS2339, Property 'set' does not exist on type 'InputSignal<...>'. The value belongs to the parent. Change it there.
  • A typo in a binding name. NG8002, Can't bind to 'stok', often together with NG8008 for the real name. Check the spelling before you check imports.
  • Changing an object you passed down. The parent shows the new value; the child keeps showing the old one, with no error. Give the parent’s signal a new object with { ...p, price: 5 }.
  • numberAttribute with text that isn’t a number. The card shows NaN and nothing fails. Prefer a bound number when the value comes from data.

A parent owns its data and binds it down; a child reads its inputs as signals and never sets them.

Exercises

Exercise 1. This page should show three stars. It doesn’t build. Why? Fix it in two different ways, one in each file.

// src/app/stars.ts
import { Component, computed, input } from '@angular/core';

@Component({
  selector: 'app-stars',
  template: `<p>{{ stars() }}</p>`,
})
export class Stars {
  readonly count = input(0);

  protected readonly stars = computed(() => '*'.repeat(this.count()));
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Stars } from './stars';

@Component({
  selector: 'app-root',
  imports: [Stars],
  template: `<app-stars count="3" />`,
})
export class App {}

Exercise 2. Write a Tag component in src/app/tag.ts, with a required text input and a tone input that defaults to 'info'. It shows the tone in capitals in square brackets, then the text. In App, use it twice: once with the text New and no tone, once with the text Low stock and the tone warn. The page should show [INFO] New and [WARN] Low stock. Hint: 'info'.toUpperCase() gives 'INFO'.

Exercise 3. A Counter child shows a count. You want a Reset button that sets the count back to 0. A first try puts the button in the child, with this.count.set(0). What does the build say? Where should the count and the button live instead? Write it without outputs.

Answers

1. count="3" passes the string "3", and count is an input of numbers, so the build fails with TS2322, Type 'string' is not assignable to type 'number'. One fix is in the parent: bind it, so the expression 3 gives a number.

// src/app/stars.ts
import { Component, computed, input } from '@angular/core';

@Component({
  selector: 'app-stars',
  template: `<p>{{ stars() }}</p>`,
})
export class Stars {
  readonly count = input(0);

  protected readonly stars = computed(() => '*'.repeat(this.count()));
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Stars } from './stars';

@Component({
  selector: 'app-root',
  imports: [Stars],
  template: `<app-stars [count]="3" />`,
})
export class App {}

The page shows:

***

The other fix is in the child: let the input accept strings, with numberAttribute. Then count="3" in the original App works:

// src/app/stars.ts
import { Component, computed, input, numberAttribute } from '@angular/core';

@Component({
  selector: 'app-stars',
  template: `<p>{{ stars() }}</p>`,
})
export class Stars {
  readonly count = input(0, { transform: numberAttribute });

  protected readonly stars = computed(() => '*'.repeat(this.count()));
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Stars } from './stars';

@Component({
  selector: 'app-root',
  imports: [Stars],
  template: `<app-stars count="3" />`,
})
export class App {}

The page shows:

***

The first fix is usually better: it keeps strict checking on the number.

2. tone has a default, text is required, and a computed builds the display:

// src/app/tag.ts
import { Component, computed, input } from '@angular/core';

@Component({
  selector: 'app-tag',
  template: `<p>{{ display() }}</p>`,
})
export class Tag {
  readonly text = input.required<string>();
  readonly tone = input('info');

  protected readonly display = computed(() => `[${this.tone().toUpperCase()}] ${this.text()}`);
}
// src/app/app.ts
import { Component } from '@angular/core';
import { Tag } from './tag';

@Component({
  selector: 'app-root',
  imports: [Tag],
  template: `
    <app-tag text="New" />
    <app-tag text="Low stock" tone="warn" />
  `,
})
export class App {}

The page shows:

[INFO] New
[WARN] Low stock

The first tag doesn’t pass tone, so it gets the default, 'info'. Both inputs are strings, so static attributes are fine here.

3. The build fails with TS2339, Property 'set' does not exist on type 'InputSignal<number>'. The count belongs to whoever changes it. Put the signal and both buttons in the parent, and let the child only show the count:

// src/app/counter.ts
import { Component, input } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `<p>Count: {{ count() }}</p>`,
})
export class Counter {
  readonly count = input.required<number>();
}
// src/app/app.ts
import { Component, signal } from '@angular/core';
import { Counter } from './counter';

@Component({
  selector: 'app-root',
  imports: [Counter],
  template: `
    <app-counter [count]="count()" />
    <button (click)="addOne()">Add one</button>
    <button (click)="count.set(0)">Reset</button>
  `,
})
export class App {
  protected readonly count = signal(0);

  protected addOne() {
    this.count.update((n) => n + 1);
  }
}

Click Add one twice, then Reset. The page shows:

Count: 0
Add oneReset

The two buttons run together as Add oneReset because buttons sit on one line. If the button really belongs inside the child, the child sends an event up and the parent resets its own signal. That’s Part 6.

What’s next

Data now flows down from parent to child, but a child can’t say anything back. In Part 6, we’ll use output() to send events up to the parent, and model() for a value that parent and child share both ways.

How useful was this post?

Click on a heart to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.