ngModel定制ValuesAccessor [英] ngModel custom ValuesAccessor
问题描述
有关ngModel和DI高级的问题。
Advanced question about ngModel and DI.
我可以在这里看到= <一个href=\"https://github.com/angular/angular/blob/2.0.0-beta.1/modules/angular2/src/common/forms/directives/ng_model.ts#L68\" rel=\"nofollow\">https://github.com/angular/angular/blob/2.0.0-beta.1/modules/angular2/src/common/forms/directives/ng_model.ts#L68
ngModel瓦亭的供应商来自NG_VALUE_ACCESSOR OpaqueToken。这意味着,如果我想创建应支持ngModel结合我应该通过我实现ValueAccessor到DI自定义组件。所以在我的脑海的两个问题。
As i can see here = https://github.com/angular/angular/blob/2.0.0-beta.1/modules/angular2/src/common/forms/directives/ng_model.ts#L68 ngModel wating for providers to come from NG_VALUE_ACCESSOR OpaqueToken. This mean if i want to create custom components which should support ngModel binding i should pass my realization of ValueAccessor to DI. So there is two questions in my mind.
1)我怎样才能做到这一点?
1) How can i do this?
2)什么是有关默认ValueAccessor为&LT;输入&GT;
元素呢?如何使它继续工作,用我只为自定义组件?
2) What's about default ValueAccessor for <input>
elements? How to make it continue to work and use mine only for custom components?
顺便说一句,因为我在这里看到:<一href=\"https://github.com/angular/angular/blob/2.0.0-beta.1/modules/angular2/src/common/forms/directives/shared.ts#L102\" rel=\"nofollow\">https://github.com/angular/angular/blob/2.0.0-beta.1/modules/angular2/src/common/forms/directives/shared.ts#L102 defaultValueAccessor是最后一次。因此,这意味着,如果我通过全球矿山ValueAccessor throught DI系统比默认的从来没有得到回报。
Btw as i see in here: https://github.com/angular/angular/blob/2.0.0-beta.1/modules/angular2/src/common/forms/directives/shared.ts#L102 defaultValueAccessor is last. So this mean if i globally pass mine ValueAccessor throught DI system than default one have never been returned.
推荐答案
您可以注册一个自定义的 ControlValueAccessor
这样的提供商在
(即绑定
一个是德precated)相应指令的属性:
You can register a custom ControlValueAccessor
like this within the providers
(the bindings
one is deprecated) attribute of the corresponding directive:
const CUSTOM_VALUE_ACCESSOR = CONST_EXPR(new Provider(
NG_VALUE_ACCESSOR,
{useExisting: forwardRef(() => TagsValueAccessor), multi: true}));
@Directive({
selector: 'tags',
host: {'(labelsChange)': 'onChange($event)'},
providers: [CUSTOM_VALUE_ACCESSOR]
})
export class TagsValueAccessor implements ControlValueAccessor {
(...)
}
然后这个访问时,将自动将使用 ngModel
和/或 ngFormControl
与选择元件选择标记
:
Then this accessor will be automatically selected when you will use ngModel
and / or ngFormControl
for the component with selector tags
:
@Component({
(...)
directives: [ TagsComponent, TagsValueAccessor ],
template: `
<tags [(ngModel)]="company.labels"
[ngFormControl]="companyForm.controls.labels"></tags>
`
})
export class DetailsComponent {
(...)
}
这方面的一个完整样本是在这个问题上可供选择:<一href=\"http://stackoverflow.com/questions/34948961/angular-2-custom-form-input/34998780#34998780\">Angular 2自定义表单输入。
希望它可以帮助你,
蒂埃里
Hope it helps you, Thierry
这篇关于ngModel定制ValuesAccessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!