我有一个简单的表单,其输入字段与一个指令相关联:
<form id="scrollable-dropdown-menu">
<input class="input-field" name="value" [someDirective] type="text" [(ngModel)]="value" #query="ngModel" />
<button (click)="onPost(query.value)" type="submit">Search</button>
</form>
该指令通过使用第三方库更改输入字段。在我的特定情况下,这是一个自动完成/预输入 Jquery 插件。该插件为用户提供选项,在选择一个选项后,它会更改输入字段的值。
但是,Angular 不会更新其属性 query.value
,因此会将旧值传递给 onPost
方法。
指令看起来像这样:
@Directive({
selector: '[someDirective]',
})
export class MyDirective {
constructor(private elRef: ElementRef, private renderer: Renderer) {
// this changes the value of the field if the user selects an option
$('.input-field').plugin();
}
}
有人建议我使用 UpdateValue,但我看不到如何在指令中使用它。这让我查看了@ViewChild,但它似乎在指令中不起作用,尽管我可能弄错了。
我还尝试通过注入(inject) ChangeDetectorRef
来强制更新,但我没有发现任何区别。这就是我所做的:
我的指令.ts
import {ChangeDetectorRef} from '@angular/core';
@Directive({
selector: '[someDirective]',
})
export class MyDirective {
constructor(private elRef: ElementRef, private renderer: Renderer, private detectorRef: ChangeDetectorRef) {
$('.input-field').plugin();
$('.input-field').my-plugin(':selected', ()=>{
// do something...
this.detectorRef.detectChanges();
})
}
}
当用户从自动完成插件中选择一个选项时,AfterSelection 被触发。对于插件,它看起来有点不同,因为它绑定(bind)到某个事件,但我认为这说明了这个想法。
如果有任何建议,我将不胜感激。
更新:
This是使用 typeahead.js 库显示主要问题的 plnkr。如果您在输入字段中写一个字母,它会显示一些选项。选择其中之一,输入字段的值将相应改变。但是,当您提交表单(单击输入字段或按回车键)时,将出现一条警告,显示传递给 onPost 函数的值是该字段的旧值,而不是您选择的自动完成值。
最佳答案
临时解决方案:Demo .将表单传递给自定义指令并使用 updateValue 手动更改值:
我的组件.ts
<form *ngIf="active" #frm="ngForm">
<input name="value" [myDirective]="frm" type="text" [(ngModel)]="value" #query="ngModel" />
<button (click)="onPost(query.value)" type="submit">Search</button>
</form>
我的指令.ts
@Directive({
selector: '[myDirective]',
})
export class MyDirective {
@Input('myDirectivev') query;
...
$(this.elRef.nativeElement).my-plugin(':selected', (ev, suggestion) => {
this.query.controls['value'].updateValue(suggestion);
});
这行得通,但如果有解决此类问题的标准方法,请告诉我。
关于javascript - Angular 2 不更新由第三方库修改的输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38289304/