Required inputs in Angular 16 or later

In Angular 16, a new feature has been added which allows for the specification of required inputs for components and directives. This means that certain inputs can be marked as necessary for a component or directive to operate as intended.

Utilizing this feature helps guarantee that all critical data is available prior to the execution of component or directive logic, leading to reduced errors, and a more efficient development process. Check angular docs for details on this


To implement this feature, set the ‘required‘ option in the input definition in child component

@Component({
  selector: 'employee',
  standalone: true,
  template: `
  <p>First Name: {{ employee.firstName }}</p>
    <p>Last Name: {{ employee.lastName }}</p>
    <p>Email: {{ employee.email }}</p>
  `,
})
export class EmployeeComponent {
  @Input({ required: true }) employee: Employee;
}

And if you try to use this in parent component and forget to pass input, you will see below error. The error might be little different based on IDE.

This will work for components and directives. In addition to v16 also added alias property, to alias the provided input.

@Component({
  selector: 'employee',
  standalone: true,
  template: `
  <p>First Name: {{ employee?.firstName }}</p>
    <p>Last Name: {{ employee?.lastName }}</p>
    <p>Email: {{ employee?.email }}</p>
  `,
})
export class EmployeeComponent {
  @Input({ required: true, alias: 'employeeInput' }) employee: Employee;
}

I created sample repository to demonstrate this. Feel free to play with it in Stackblitz

Pavan Kumar Jadda
Pavan Kumar Jadda
Articles: 36

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.