我最近开始学习 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'});
}
}
然后我将它绑定(bind)到组件中的输入元素中,如下所示:
@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(){
}
}
Here is a plunker with my example
当我开始在输入中输入内容时 - 到我的 FormGroup
的绑定(bind)按预期工作。但是当我从自动完成中选择一些提示时 - 它会更新输入,但不会将更新后的值传播到我的表单组。
所以我的问题是,是否可以向表单组发送有关指令中发生的更改的信号?
一个可能的解决方案是制作一个实现 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()"
/>
关于jquery - 在 Angular 世界之外发生更改时如何更新 Angular 2 Reactive 表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44558732/