使用指令 Angular 2 更改输入的 ngModel 值
Change an input's ngModel value using a directive Angular 2
我无法理解如何使用指令访问和更改输入 ngModel
值。问题的结果是,当我 select 所需地址时,模型的地址值不会更新...它只是设置为我实际输入到输入中的内容,而不是输入的最终值。
我输入“830”:
I select '8300 Fauntleroy Way Southwest, Seattle, WA, United States':
结果值:
{
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());
});
});
}
}
})();
但现在我正在尝试转换它 Angular2,我有点卡住了。到目前为止,这是我对转换的了解:
/// <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());
的事情。
如有任何帮助,我们将不胜感激。
我会注入与您的输入相关联的 ControlValueAccessor
。这是一个示例:
@Directive({
selector: '[test]'
})
export class TestDirective {
constructor(@Inject(NG_VALUE_ACCESSOR) private valueAccessor:ControlValueAccessor) {
setTimeout(() => {
this.valueAccessor[0].writeValue('test');
}, 1000);
}
}
例如,请参阅此 plunkr:https://plnkr.co/edit/owhBHdBncAxlzwJ8xkfq?p=preview。
我最终让它起作用了,尽管我不明白为什么它起作用,因为我没有将 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>
这是我用我的日期选择器所做的,可能会有帮助。
//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);
}
});
}
我无法理解如何使用指令访问和更改输入 ngModel
值。问题的结果是,当我 select 所需地址时,模型的地址值不会更新...它只是设置为我实际输入到输入中的内容,而不是输入的最终值。
我输入“830”:
I select '8300 Fauntleroy Way Southwest, Seattle, WA, United States':
结果值:
{
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());
});
});
}
}
})();
但现在我正在尝试转换它 Angular2,我有点卡住了。到目前为止,这是我对转换的了解:
/// <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());
的事情。
如有任何帮助,我们将不胜感激。
我会注入与您的输入相关联的 ControlValueAccessor
。这是一个示例:
@Directive({
selector: '[test]'
})
export class TestDirective {
constructor(@Inject(NG_VALUE_ACCESSOR) private valueAccessor:ControlValueAccessor) {
setTimeout(() => {
this.valueAccessor[0].writeValue('test');
}, 1000);
}
}
例如,请参阅此 plunkr:https://plnkr.co/edit/owhBHdBncAxlzwJ8xkfq?p=preview。
我最终让它起作用了,尽管我不明白为什么它起作用,因为我没有将 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>
这是我用我的日期选择器所做的,可能会有帮助。
//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);
}
});
}