jquery - 在 Angular 世界之外发生更改时如何更新 Angular 2 Reactive 表单字段

标签 jquery angular angular2-forms angular2-directives angular-directive

我最近开始学习 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/

相关文章:

javascript - 中心对齐网格没有间隙和 float

Angular2 获取表单控件的现有验证器

Angular2 ngModel 选择 - 处理一个对象

angular - 以编程方式设置 <mat-select> 的值

jQuery 文本框光标到文本末尾?

jquery - 如何在 jQuery 中迭代类?

javascript - Jquery 滚动动画滚动到 div 的底部而不是顶部

javascript - 我们可以在 Angular 中使用 Jasmine/Karma 测试 ngrx 流吗?

javascript - Angular 9在单个元素滚动上添加类

angular - 找不到模块 '@angular/core/src/metadata/lifecycle_hooks' - primeng/table/table.d.ts