我正在阅读下面的文章,并且我尝试在与ngModel和ngControl集成的角度2中实现自定义控件。
文章:http://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel
但我很难抽出如何在发出事件时获取更新的模型值。它似乎在事件更新之前使用了模型。
这是一个带有示例的plunker:
https://plnkr.co/edit/ixK6UxhhWZnkFyKfbgky
我做错了什么?
main.ts
$('#extra_crew_area').find(".form-control:last input[type='text']").val(extra_crew);
app.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {App} from './app';
bootstrap(App, [])
.catch(err => console.error(err));
自定义-input.component.ts
import {Component} from '@angular/core'
import {FORM_DIRECTIVES} from "@angular/common";
import {CustomInput} from './custom-input.component'
@Component({
selector: 'my-app',
providers: [],
template: `
<form (ngSubmit)="onSave()" #demoForm="ngForm">
<div class="row info-row">
<span class="col-xs-12">
<p><span class="boldspan">Form data:</span>{{demoForm.value | json}}</p>
<p><span class="boldspan">Model data:</span> {{dataModel}}</p>
</span>
</div>
<custom-input ngControl="someValue" ref-input (onKeyDown)="onKeyDown(input)" [(ngModel)]="dataModel">Enter data:</custom-input>
</form>
`,
directives: [CustomInput, FORM_DIRECTIVES]
})
export class App {
dataModel: string = '';
onKeyDown(event){
console.log(event._value);
console.log(this.dataModel);
}
}
答案 0 :(得分:0)
我认为问题在于您混合了自定义输出和已注册的回调。在这种情况下,不需要自定义输出。
您可以利用ngModelChange
组件中的CustomInput
事件来调用_onChangeCallback
回调:
@Component({
selector: 'custom-input',
template: `
<div class="form-group">
<label><ng-content></ng-content>
<input class="form-control" [(ngModel)]="value"
(ngModelChange)="onModelChange($event)"
(keydown)="onKeyDownEvent($event)"
(blur)="onTouched()">
</label>
</div>
`,
(...)
export class CustomInput implements ControlValueAccessor {
(...)
onModelChange(value) {
this.value = value;
this._onChangeCallback(value);
}
}
在这种情况下,你的getter和setter不再是必需的了。
这篇文章也可能让您感兴趣(第34节;与NgModel兼容的组件&#34;):