我想在使用属性Directive键入时更改(强制)输入字段值.有了它,我想创建一些指令,如大写,小写,maxlength,filterchar等,用于表单上的输入字段.我找到了这个例子:Angular 2 Attribute Directive Typescript Example但这似乎不起作用.也许它是为早期构建的Angular2做的.然而,这正是我想要做的.
当我创建这样的指令时:
import {Directive} from 'angular2/core';
import {NgModel} from 'angular2/common';
@Directive({
selector: '[ngModel][uppercase]',
host: {
'(input)' : 'onInputChange()'
}
})
export class UppercaseDirective{
constructor(public model:NgModel){}
onInputChange(){
var newValue = this.model.value.toUpperCase();
this.model.valueAccessor.writeValue(newValue);
this.model.viewToModelUpdate(newValue);
}
}
Run Code Online (Sandbox Code Playgroud)
并在这样的表单上使用它:
<input type="text" class="form-control" [(ngModel)]="field.name" ngControl="name" #name="ngForm" required uppercase>
Run Code Online (Sandbox Code Playgroud)
(并注册NgModel为提供者).我得到了
undefined this.model.value.
我可以使用$event.target.value = $event.target.value.toUpperCase()(当传递$event时onInputChange())并且适用于视图(它确实将输入显示为大写.但它不会更新绑定字段"field.name".
那么如何创建一个Angular2属性指令呢?
- 编辑 -
经过一番进一步调查后,我设法得到了我想要的东西.Günter提供的答案更接近我的初衷,也许更好.但这是另一种方式:
import {Directive, Input, Output, EventEmitter} from 'angular2/core';
@Directive({
selector: '[ngModel][uppercase]',
host: …Run Code Online (Sandbox Code Playgroud) 使用AngularFire2我尝试从单个Firestore文档中获取数据.有效的是:
this.addressRef = afs.doc<Address>('addresses/key')
this.addressRef.valueChanges().subscribe(val => {......}
Run Code Online (Sandbox Code Playgroud)
我想只运行一次订阅代码.通常我使用take(1)来实现这一点(与Firebase DB一起使用).但是这段代码:
this.addressRef.valueChanges().take(1).subscribe(val => {......}
Run Code Online (Sandbox Code Playgroud)
给出错误:TypeError:this.addressRef.valueChanges(...).take不是函数.
VS Code列出了采取行动.这是AngularFire2中的一个错误,我做错了还是有其他(更好的)方法在获取数据后停止订阅?我也尝试过topromise,但这也失败了.