sha*_*ine 9 angular2-directives angular
我坚持如何ngModel使用指令访问和更改输入值.问题的结果是,当我选择所需的地址时,模型的地址值不会更新...它只是设置为我实际键入输入的内容,而不是输入的最终值.
我键入'830':
我选择'8300 Fauntleroy Way Southwest,Seattle,WA,United States':
结果价值:
{
address: '830'
}
Run Code Online (Sandbox Code Playgroud)
期望值:
{
address: '8300 Fauntleroy Way Southwest, Seattle, WA, United States'
}
Run Code Online (Sandbox Code Playgroud)
在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());
});
});
}
}
})();
Run Code Online (Sandbox Code Playgroud)
但是现在我正在尝试将它转换为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));
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
<input type="text"
ngControl="address"
placeholder="Enter a location"
[(ngModel)]="subject.address"
#address="ngForm"
google-places
required>
Run Code Online (Sandbox Code Playgroud)
问题的核心是我不明白如何model.$setViewValue(element.val());在Angular 2中做相同的事情.
任何帮助将不胜感激.
我最终使它起作用,尽管我不明白为什么它起作用,因为我没有绑定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));
});
}
}
Run Code Online (Sandbox Code Playgroud)
组件模板:
<input type="text"
class="form-control"
ngControl="address"
id="subjectAddress"
placeholder="Enter a location"
[(ngModel)]="subject.address"
#address="ngForm"
google-places
required>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10496 次 |
| 最近记录: |