如何在 Angular 世界之外发生更改时更新 Angular 2 反应式表单字段



我最近开始学习 Angular 2,我正在努力理解如何将外部世界发生的变化与 Angular Reactive Forms 正确联系起来。

具体来说,我对以下示例有问题: 我想创建一个指令,通过 typeahead jQuery 插件提供的自动完成功能来增强输入。我的指令如下所示:

@Directive({
selector: '[myTypeahead]'
})
class TypeAheadDirective implements AfterViewInit 
{
constructor(private el: ElementRef) {
}
//this will be used as a parameter to source, it is not important for this example
@Input() myTypeahead: string;
ngAfterViewInit() {
let source = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
prefetch: 'http://twitter.github.io/typeahead.js/data/films/post_1960.json'
});
$(this.el.nativeElement).typeahead(null, {source, display: 'value'});
}
}

然后我把它绑定到我的组件的输入元素中,如下所示:

@Component({
selector: 'my-app',
template: `
<form (ngSubmit)="save()" [formGroup]="someForm">
<h2>Hello {{name}}</h2>
<input formControlName="name" myTypeahead="'http://someRemoteUrl'"/>
</form>
<div class="example">Form model: {{someForm.value | json}}</div>
`,
})
export class App implements OnInit {
someForm: FormGroup;
name:string;
constructor(private fb: FormBuilder) {
this.name = `Angular! v${VERSION.full}`
}
ngOnInit() {
this.someForm = this.fb.group({
name: ''
});
}
save(){
}
}

这是我的例子

当我开始在输入中键入内容时 - 与FormGroup的绑定按预期工作。但是当我从自动完成中选择一些提示时 - 它会更新输入,但不会将更新的值传播到我的表单组。

所以我的问题是,是否可以向表单组发出有关指令中发生的变化的信号?

一个可能的解决方案可能是创建一个实现ControlValueAccessor通知更改的组件,但我想通过接受数据源 URL 的指令来保持这件事简单。

内部指令:

您可以使用@Output发送事件并在表单中捕获它

@Output typeaheadResult = new EventEmitter(); 
...
// Whenever user selects a result dispatch the event 
this.typeaheadResult.emit(changedInput);

在你的HTML中,你可以捕获它

<input formControlName="name"
myTypeahead="'http://someRemoteUrl'"
(typeaheadResult)="doSomething()"
/>

最新更新