From Good to Great: Required Inputs in Angular

Netanel Basal
Netanel Basal
Published in
2 min readMar 23, 2023

--

A new feature introduced in Angular 16.0.0-next.4 is the ability to define inputs as required for components and directives. In other words, we can now specify that a component or directive requires certain inputs to function properly.

By using this new feature, we can ensure that all necessary data is present before the component or directive logic is executed, resulting in better code quality, fewer errors, and an overall more efficient development process. To use it we can set the new required option in our input:

@Component({
selector: 'app-foo',
standalone: true,
templateUrl: './foo.component.html',
})
export class FooComponent {
👇
@Input({ required: true }) elementId: string;
}

There will be a compilation error if the consumer doesn’t initialize this input:

We can also pass an alias using the new alias option:

@Component({
selector: 'app-foo',
standalone: true,
templateUrl: './foo.component.html',
})
export class FooComponent {
👇
@Input({ required: true, alias: 'elementId' }) id: string;
}

This feature also works with host directives. It means that if we consume a directive using hostDirectives, we must expose its required inputs.

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.