Angular2 - 表单中的自定义指令不当行为

标签 angular angular2-directives angular2-forms angular2-components

我在使用 <input ...> 的自定义指令时遇到问题当标签位于 Angular 表单内时,它的模板中的标签。

如果您在表单内声明输入,则编辑输入字段将按照预期更改表单的属性,例如原始、触摸、有效等。

如果您在表单中声明自定义指令,例如 <ac2-string-input ...></ac2-string-input>并且它的模板包含一个输入,那么如果您编辑此输入的字段,它不会更改表单的属性。

这是为什么呢?这是一个错误吗?有什么解决办法吗?

下面有一个示例:

我们可以在app/form.component.ts中拥有一个表单组件

import { Component } from '@angular/core'

import { InputComponent } from './input.component'

@Component({
    selector: 'ac2-form',
    templateUrl: '<build path>/templates/form/form.html',
    directives: [InputComponent]
})

export class FormComponent {


    item: Object = {
       attr1: 'blah',
       attr2: 'another blah'
    }

    constructor(){}

    submit(){ console.log(this.item) }
}

使用模板templates/form/form.html

<form #f="ngForm" (ngSubmit)="submit()">
  <input type="text" name="attr1" [(ngModel)]="item.attr1"/>
  <ac2-string-input [obj]="item"></ac2-string-input>

  <button type="submit">Submit</button>
</form>

<div>
    Pristine? {{f.form.pristine}}
</div>

并且ac2-string-input指令在app/form/input.component.ts

中定义
import { Component, Input } from '@angular/core'

@Component({
    selector: 'ac2-string-input',
    templateUrl: '<build path>/templates/form/input.html'
})

export class InputComponent {
    @Input() obj: Object;

    constructor(){}
}

使用模板templates/form/input.html

<input type="text" name="attr2" [(ngModel)]="obj.attr2"/>

如果我们加载表单,将会有两个文本字段,并且表单将为“Pristine”

Form

如果我们编辑“attr2”字段,表单将继续保持原始状态,就好像该字段未绑定(bind)到表单一样!

field edited, form pristine

如果我们编辑“attr1”字段,表单将不会像预期的那样保持原始状态。

最佳答案

我打开了一个 issue在 Angular 2 的 github 中。

事实证明,如果我们希望我们的组件被识别为表单控件,我们需要实现 ControlValueAccessor 接口(interface)并将 ngModel 放在顶层。

THIS Plunkr 展示了如何做到这一点。

积分转到kara谁帮我解决了这个问题。

关于Angular2 - 表单中的自定义指令不当行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39323179/

相关文章:

javascript - Angular:如何将自定义指令中的索引变量共享给另一个指令?

Angular 2 - 复选框不同步

angular - 订阅服务

angular - 在 angular2 中提交表单时显示错误消息?

angular - 扩展 BaseRequestOptions 时未定义注入(inject)的依赖项

typescript - angular 2自定义指令OnInit

Angular PrimeNG 日期时间选择器

angular - 在 child 中获取父指令

angular - 我如何将一个类导出到模块并在带 Angular typescript 中将其导入另一个模块

javascript - 遍历 Angular 2 中的嵌套 FormArray