我有一个完整的模板自动完成:
<input [(ngModel)]="model"> //todo add control
它实现如下:
<div class="form-group"> <label for="location">Location</label> <auto-complete [(model)]="model.location"></auto-complete> </div>
除此之外,我还有其他字段遵循以下格式:(通知验证指令)
<div class="form-group" [fieldValidity]="biography"> <label for="currentPassword">Biography</label> <textarea [(ngModel)]="model.biography" ngControl="biography" #biography="ngForm" maxlength="300" class="form-control" placeholder="About me..." rows="4"></textarea> <p class="xui-Meta-info"> We suggest a short bio. If it's 300 characters or less it'll look great on your profile. </p> <field-validation-messages [field]="biography"></field-validation-messages> </div>
如您所见,我的验证指令依赖于在表单上具有关联控件的输入.如何确保自动完成输入在父表单中具有关联控件? (我尝试以编程方式创建一个新的Control(),然后调用form.addControl(),但只接受一个NgControl
您需要通过实现自定义值访问器使您的自动完成组件与控件兼容.
原文链接:https://www.f2er.com/angularjs/142525.html这是一个示例:
@Component({ selector: 'auto-complete',template: ` <input [(ngModel)]="model" (ngModelChange)="onChange($event)> `,(...) }) export class AutoCompleteComponent implements AfterViewInit,ControlValueAccessor { onChange = (_) => {}; onTouched = () => {}; writeValue(value: any): void { this.model = value; } registerOnChange(fn: (_: any) => void): void { this.onChange = fn; } registerOnTouched(fn: () => void): void { this.onTouched = fn; } }
<auto-complete [(model)]="model.location" [ngFormControl]="someCtrl"> <!-- or #autoComplete="ngForm" ngControl="autoComplete" --> </auto-complete>
有关更多详细信息,请参阅此文章(“与NgModel兼容的组件”部分):
> http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/
这个问题也可以帮到你: