使用指令 Angular 2 更改输入的 ngModel 值 [英] Change an input's ngModel value using a directive Angular 2

查看:41
本文介绍了使用指令 Angular 2 更改输入的 ngModel 值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在如何使用指令访问和更改输入 ngModel 值.问题的结果是,当我选择所需的地址时,模型的地址值不会更新……它只是设置为我在输入中实际键入的内容,而不是输入的最终值.

I'm stuck on how to access and change an inputs ngModel value using a directive. The outcome of the issue is that the model's address value doesn't update when I select the desired address...it's just set to what I actually typed into the input, rather than final value of the input.

我输入830":

我选择8300 Fauntleroy Way Southwest, Seattle, WA, United States":

结果值:

{
  address: '830'
}

期望值:

{
  address: '8300 Fauntleroy Way Southwest, Seattle, WA, United States'
}

在 AngularJS 中,我可以这样做:

In AngularJS I could do this:

(function() {
  'use strict';

  angular
  .module('casemanagerApp')
  .directive('googleplace', googleplace);

  function googleplace() {

    var directive = {
      require: 'ngModel',
      link: link
    };

    return directive;

    function link(scope, element, attrs, model) {
      var options = {
        types: [],
        componentRestrictions: {}
      };
      scope.gPlace = new google.maps.places.Autocomplete(element[0], options); // jshint ignore:line

      google.maps.event.addListener(scope.gPlace, 'place_changed', function() { // jshint ignore:line
        scope.$apply(function() {
          model.$setViewValue(element.val());
        });
      });
    }
  }

})();

但是现在我正在尝试将其转换为 Angular 2,我有点卡住了.到目前为止,这是我对转换的了解:

But now that I'm trying to convert it Angular 2, I'm a little stuck. Here's what I have so far on the conversion:

/// <reference path="../../../../typings/browser/ambient/googlemaps/index.d.ts"/>

import { Directive, ElementRef, OnInit } from '@angular/core';

@Directive({
  selector: '[google-places]'
})
export class GooglePlaces implements OnInit {

  constructor(private _el: ElementRef) { }

  ngOnInit() {
    let gPlace = new google.maps.places.Autocomplete(this._el.nativeElement);
    google.maps.event.addListener(gPlace, 'place_changed', () => console.log(this._el.nativeElement));
  }

}

用法:

<input type="text"
       ngControl="address"
       placeholder="Enter a location"
       [(ngModel)]="subject.address"
       #address="ngForm"
       google-places
       required>

问题的核心是我不明白如何在 Angular 2 中执行 model.$setViewValue(element.val()); 的等效操作.

The heart of the issue is I don't understand how to do the equivalent of model.$setViewValue(element.val()); in Angular 2.

如有任何帮助,我们将不胜感激.

Any assistance would be greatly appreciated.

Plunker

推荐答案

我最终得到了这个,虽然我不明白为什么它会起作用,因为我没有将 ngModelChange 绑定到元素...但它有效.

I ended up getting this to work, although I don't understand why it works because I'm not binding ngModelChange to the element...but it works.

指令:

/// <reference path="../../../../typings/browser/ambient/googlemaps/index.d.ts"/>

import { Directive, ElementRef, Output, EventEmitter, OnInit, NgZone } from '@angular/core';

@Directive({
  selector: '[google-places]'
})
export class GooglePlaces implements OnInit {
  @Output() ngModelChange: EventEmitter<any> = new EventEmitter(false);

  options = {
    types: ['address'],
    componentRestrictions: { country: "us" }
  };

  constructor(
    private _el: ElementRef,
    private _ngZone: NgZone) { }

  ngOnInit() {
    let gPlace = new google.maps.places.Autocomplete(this._el.nativeElement, this.options);
    google.maps.event.addListener(gPlace, 'place_changed', () => {
      this._ngZone.run(() =>
        this.ngModelChange.emit(this._el.nativeElement.value));
    });
  }

}

组件模板:

<input type="text"
            class="form-control"
            ngControl="address"
            id="subjectAddress"
            placeholder="Enter a location"
            [(ngModel)]="subject.address"
            #address="ngForm"
            google-places
            required>

这篇关于使用指令 Angular 2 更改输入的 ngModel 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆