ngModel for two-way binding. What will be the value of username after the user types 'Alice' in the input box?import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-user-input', standalone: true, template: ` <input [(ngModel)]="username" aria-label="Username input" /> <p>Hello, {{ username }}!</p> `, imports: [FormsModule] }) export class UserInputComponent { username = ''; }
The ngModel directive requires importing FormsModule in the component or module. Without it, Angular throws an error because it doesn't recognize ngModel. So even though the code looks correct, it will cause a runtime error.
email after typing 'test@example.com'?ngModel, what will be the value of the email property after the user types 'test@example.com' in the input field?import { Component } from '@angular/core'; import { FormsModule } from '@angular/forms'; @Component({ selector: 'app-email-input', standalone: true, template: ` <input [(ngModel)]="email" aria-label="Email input" /> <p>Your email is: {{ email }}</p> `, imports: [ FormsModule ] }) export class EmailInputComponent { email = ''; }
With [(ngModel)], the input value and the component property email stay in sync. When the user types 'test@example.com', the email property updates immediately to that string.
password property to an input field using Angular's two-way binding syntax.The [(ngModel)]="password" is Angular's shorthand for binding the property and listening to changes. Option A separates these but is more verbose and less common. Option A is one-way binding only.
name property?ngModel for two-way binding, but typing in the input does not update the name property. What is the cause?import { Component } from '@angular/core'; @Component({ selector: 'app-name-input', standalone: true, template: ` <input [(ngModel)]="name" aria-label="Name input" /> <p>Name: {{ name }}</p> `, imports: [] }) export class NameInputComponent { name = 'John'; }
Without importing FormsModule, Angular does not recognize ngModel, so the binding does not work and the property does not update.
ngModel?Angular's two-way binding with [(ngModel)] is syntactic sugar for combining property binding [ngModel] and event binding (ngModelChange). This keeps the input and component property in sync.