Sunday, May 7, 2023

Angular- Required Component Inputs in Angular16

Required Component Inputs in Angular16

Angular16 has introduced a new feature to define the inputs as required for component and directives. We can now specify that a component or directive requires certain inputs to function properly.

By using this new feature, we can insure that all necessary data is present before the component or directive logic/functionality executed, resulting better code quality, fewer errors. To use it we can set the new required option in our input:

1
2
3
4
5
6
7
8
9
10
import { Component, Input } from '@angular/core';
 
@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
})
export class MyComponentComponent {
  @Input({ required: true }) elementId: string;
}

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

required component inputs

We can use the new alias option to pass the alias for input:

1
2
3
4
5
6
7
8
9
10
import { Component, Input } from '@angular/core';
 
@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css'],
})
export class MyComponentComponent {
  @Input({ required: true, alias: 'elementId' }) id: string = '';
}

In the above we have define a input id and givent the alias name elementId. In the cosumer component we can use this alias name to pass the input valuse as below-

1
<app-my-component [elementid]="'component1'"></app-my-component>

No comments:

Post a Comment