Return to site

๐Ÿ…ฐ NEW In Angular: Required for @Input

ยท angular

With Angular 16, you can use the {๐‘Ÿ๐‘’๐‘ž๐‘ข๐‘–๐‘Ÿ๐‘’๐‘‘:๐‘ก๐‘Ÿ๐‘ข๐‘’} option for an @๐ผ๐‘›๐‘๐‘ข๐‘ก() decorator to make a property mandatory.

This means that the component will only work if you pass a value for that property.

๐Ÿ‘จโ€๐Ÿ’ป๏ผฃ๏ผฏ๏ผค๏ผฅใ€€๏ผณ๏ผฎ๏ผฉ๏ผฐ๏ผฐ๏ผฅ๏ผด

// ๐’‚๐’‘๐’‘.๐’„๐’๐’Ž๐’‘๐’๐’๐’†๐’๐’•.๐’•๐’”
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<h1>Angular 16 Example</h1>
<app-greeting [name]="name"></app-greeting>
<app-greeting></app-greeting> // This will cause an error
`
})
export class AppComponent {
name = 'Alice';
}

// ๐’ˆ๐’“๐’†๐’†๐’•๐’Š๐’๐’ˆ.๐’„๐’๐’Ž๐’‘๐’๐’๐’†๐’๐’•.๐’•๐’”
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-greeting',
template: `
<p>Hello, {{name}}!</p>
`
})
export class GreetingComponent {
@๐ˆ๐ง๐ฉ๐ฎ๐ญ({๐ซ๐ž๐ช๐ฎ๐ข๐ซ๐ž๐:๐ญ๐ซ๐ฎ๐ž}) ๐ง๐š๐ฆ๐ž? :๐ฌ๐ญ๐ซ๐ข๐ง๐ ; // This property is mandatory
}

โŒ๏ผฅ๏ผฒ๏ผฒ๏ผฏ๏ผฒ

If the name property of GreetingComponent is not filled, the error message will be something like this:

๐ธ๐‘Ÿ๐‘Ÿ๐‘œ๐‘Ÿ: ๐‘€๐‘–๐‘ ๐‘ ๐‘–๐‘›๐‘” ๐‘Ÿ๐‘’๐‘ž๐‘ข๐‘–๐‘Ÿ๐‘’๐‘‘ @๐ผ๐‘›๐‘๐‘ข๐‘ก() ๐‘“๐‘œ๐‘Ÿ ๐‘๐‘œ๐‘š๐‘๐‘œ๐‘›๐‘’๐‘›๐‘ก ๐บ๐‘Ÿ๐‘’๐‘’๐‘ก๐‘–๐‘›๐‘”๐ถ๐‘œ๐‘š๐‘๐‘œ๐‘›๐‘’๐‘›๐‘ก: ๐‘›๐‘Ž๐‘š๐‘’

#angular #angular16 #requiredInput #programming