Angular 2将控件添加到父组件的窗体 [英] Angular 2 Add control to parent component's form

查看:56
本文介绍了Angular 2将控件添加到父组件的窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自动完成的模板:

I have an autocomplete complete with template:

<input [(ngModel)]="model"> //todo add control

其实现方式如下:

<div class="form-group">
  <label for="location">Location</label>
  <auto-complete [(model)]="model.location"></auto-complete>
</div>

除此之外,我还有其他遵循此格式的字段:(注意验证指令)

Alongside it, I have other fields which follow this format: (Notice validation directives)

<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

As you can see, my validation directives rely on the input having an associated control on the form. How can I ensure my input in auto complete has an associated control in the parent form? (I've tried programmatically creating a new Control() and then calling form.addControl() but that only accepts an NgControl

推荐答案

您需要通过实现自定义值访问器使auto-complete组件与控件兼容.

You need to make your auto-complete component compliant with control by implementing a custom value accessor.

以下是示例:

@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; }
}

通过这种方式,您可以通过以下方式直接添加对您的自动完成组件的控制:

This way you can directly add control your auto complete component this way:

<auto-complete
  [(model)]="model.location"
  [ngFormControl]="someCtrl">
  <!-- or #autoComplete="ngForm" ngControl="autoComplete" -->
</auto-complete>

有关更多详细信息,请参见本文(与NgModel兼容的组件"一节):

For more details, see this article (section "NgModel-compatible component"):

此问题也可以为您提供帮助:

This question could also help you:

这篇关于Angular 2将控件添加到父组件的窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆