Angular 5 ngModelOptions多事件更新问题及实现方案问询
Hey there! Let's break down your question and walk through practical solutions for this scenario.
First, the straight answer: Angular 5 does NOT support passing multiple events to updateOn via space-separated strings like Angular 1 did. The updateOn option in ngModelOptions only accepts a single event name (like 'blur' or 'submit') in this version.
But don't worry—there are solid ways to achieve exactly what you want: updating the model on both blur and enter/submit. Here are a few approaches, including the one you're already considering:
Option 1: Trigger Blur on Enter (Your Proposed Approach)
Since you already have updateOn: 'blur' working, this is a straightforward tweak. Just listen for the enter key on your input and manually trigger a blur event, which will kick off the model update you already have set up.
Here's how to implement it in your template:
<input type="text" [(ngModel)]="yourModelValue" [ngModelOptions]="{updateOn: 'blur'}" (keyup.enter)="$event.target.blur()" >
When the user presses enter, the input will blur, triggering the existing blur-based model update. This keeps your existing logic intact while adding the enter key functionality.
Option 2: Manually Trigger Model Update
If you'd prefer not to rely on the blur event, you can directly trigger the model update using the NgModel directive's API. First, assign a template reference to the input to access the NgModel instance:
<input type="text" [(ngModel)]="yourModelValue" [ngModelOptions]="{updateOn: 'blur'}" #inputModel="ngModel" (keyup.enter)="inputModel.update.emit(inputModel.value)" >
The update.emit() method forces the model to sync with the input's current value, so this will update the model on enter while still respecting the blur update behavior.
Option 3: Custom Directive (For Reusable Code)
If you need this behavior across multiple inputs in your app, creating a custom directive is a cleaner, more maintainable solution. It encapsulates the logic so you don't have to repeat event listeners everywhere.
Here's a simple directive you can use:
import { Directive, HostListener, Self } from '@angular/core'; import { NgModel } from '@angular/forms'; @Directive({ selector: '[updateOnBlurAndEnter]' }) export class UpdateOnBlurAndEnterDirective { constructor(@Self() private ngModel: NgModel) { // Set default update trigger to blur this.ngModel.options.updateOn = 'blur'; } @HostListener('keyup.enter') handleEnterKey() { // Manually trigger model update on enter this.ngModel.update.emit(this.ngModel.value); } }
Then, just add the directive to any input that needs the dual update behavior:
<input type="text" [(ngModel)]="yourModelValue" updateOnBlurAndEnter >
This way, all inputs with the directive will automatically update on both blur and enter, no extra event listeners needed.
内容的提问来源于stack exchange,提问作者noah lubko

