🅰️NGULAR1️⃣6️⃣: How can you make an input property required in Angular 16 using the new syntax?
🅰️NGULAR1️⃣6️⃣: How can you make an input property required in Angular 16 using the new syntax?
🅰️NGULAR1️⃣6️⃣: How can you make an input property required in Angular 16 using the new syntax?
* @Input({ required: true }) name: string;
* @Input('name', { required: true }) name: string;
* @Input() name: string = required;
* @Input() required name: string;
#angular #angular16 #interviewquestion #fullstack
Answer:
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.
Code snippet:
// app.component.ts 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'; }; // greeting.component.ts import { Component, Input } from '@angular/core' @Component({ selector: 'app-greeting', template: ` <p>Hello, {{name}}!</p> ` }) export class GreetingComponent { @Input({required:true}) name? :string; // This property is mandatory };
Error:
If the name property of GreetingComponent is not filled, the error message will be something like this:
Error: Missing required @Input() for component GreetingComponent: name
GitHub Demo: https://github.com/vinny59200/VV-ng16-reuired-input