Angular 16 Required Input with Example

Angular 16 Required Input with Example

The ability to declare inputs that are required for components and directives is a new feature added in Angular 16. In other words, we can now indicate that specific inputs are required for a component or directive to perform properly.

Using this new feature, we can guarantee that all relevant data is available before executing the component or directive logic, resulting in greater code quality, fewer mistakes, and a more efficient development process overall. To use it, we may add the following new required option to our input:

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

If the end user does not initialize this input, a compilation error will occur.

This functionality is also compatible with host directives. It indicates that if we use hostDirectives to consume a directive, we must disclose its needed inputs.