使用指令Angular 2更改输入的ngModel值

时间:2016-06-02 17:51:38

标签: angular angular2-directives

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

我输入'830':

enter image description here

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

enter image description here

结果值:

{
  address: '830'
}

期望值:

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

在AngularJS中,我可以这样做:

(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,我有点卡住了。这是我到目前为止转换的内容:

/// <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());的等效操作。

非常感谢任何协助。

Plunker

3 个答案:

答案 0 :(得分:5)

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

<强>指令:

/// <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>

答案 1 :(得分:1)

我会注入与您的输入相关联的do { let predicate = NSPredicate(format: "categoryName == %@", "yourCategoryHere") let fetchSubcategory = NSFetchRequest(entityName: "Subcategory") fetchSubcategory.predicate = predicate if let subCategoryResults = try context.executeFetchRequest(fetchSubcategory) as? [Subcategory] { //do stuff } let fetchItem = NSFetchRequest(entityName: "Item") fetchItem.predicate = predicate if let itemResults = try context.executeFetchRequest(fetchItem) as? [Item] { //do stuff } }catch { print(error) } 。这是一个示例:

ControlValueAccessor

请参阅此plunkr例如:https://plnkr.co/edit/owhBHdBncAxlzwJ8xkfq?p=preview

答案 2 :(得分:0)

这就是我用我的日期选择器做的,可能会有帮助。

//Create a method in your component to change the model
dateChanged(date) {
   this.hero.bday = date;
}

public ngOnInit() {
    //CREATE A REFERERENCE TO YOUR COMPONENT
    var component:CreateEventComponent = this;
    $("#bday").datepicker({
        dateFormat: "dd-mm-yy",
        altFormat: "dd-mm-yy",
        onSelect: function (dateText, datePicker) {
            //UPDATE YOUR MODEL FORM JQUERY CODE.
            component.dateChanged(dateText);
        }
    });
}