加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

twitter-bootstrap – 将angular2表单指令应用于自定义输入表单

发布时间:2020-12-17 21:30:44 所属栏目:安全 来源:网络整理
导读:我想创建一个自定义InputCustom组件并使用它来创建模型驱动的表单. 我的自定义组件只包含一个输入字段,并使用Bootstrap材质设计来表示“感觉”. @Component({ selector:'inputCustom',template:` div class="form-group label-floating is-empty" label clas
我想创建一个自定义InputCustom组件并使用它来创建模型驱动的表单.

我的自定义组件只包含一个输入字段,并使用Bootstrap材质设计来表示“感觉”.

@Component({
 selector:'inputCustom',template:`
    <div class="form-group label-floating is-empty">
        <label class="control-label" for="input">Type here</label>
        <input class="form-control" id="input" type="text">
        <p class="help-block">Some help text</p>
        <span class="material-input"></span>
    </div>
`})
class InputCustom{....}

在Angular2中创建模型驱动的表单时

<form [ngFormModel]="formRef">
    <input type ="email" ngControl="email">
</form>

表单元素上的所有控件都注册到ControlGroup中.通过使用formRef,您可以跟踪控制器内的字段值.

@Component({...})
class FormController{
    formRef: ControlGroup;
    constructor(...){
        this.form.valueChanges.subscribe(data => console.log('changes',data));
    }
}

现在,我希望人们像这样使用我的组件

<form [ngFormModel]="formRef">
    <inputCustom type ="email" ngControl="email">
</form>

Q1:我是否需要编写自己的自定义ngControl指令?

Q2:如何将ngControl传播到内部< input>由< inputCustom&gt ;?包裹的元素 问题3:我应该如何在周围的表单ControlGroup中注册我的Control?

解决方法

我认为有两种方法可以实现:

>将您的控件作为自定义组件的参数提供:

@Component({
  selector: 'inputCustom',template: `
    <input [ngFormControl]="control"/>
  `
export class FormFieldComponent {
  (...)
  @Input()
  control: Control;
}

这样,您的输入将自动获取父组件中定义的表单的一部分.
>实现符合ngModel的组件.实现起来要长一些(您需要在自定义指令中实现并注册ControlValueAccessor),但这样您就可以直接在自定义组件上直接使用ngFormControl和ngModel.

<inputCustom type ="email" [ngFormControl]="email">

有关更多详细信息,请参阅此问题:Angular 2 custom form input

我认为这篇文章会引起你的兴趣:

>实施Angular2表格 – 超越基础(第2部分) – http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读