如何使用Angular中的输入创建自定义组件并将其绑定到窗体



假设我们有这样的

<form #f="ngForm" (ngSubmit)="onSubmit()">
<rc-some-component ngModel name="someComponent"></rc-some-component>
<label for="fname">First name:</label>
<input ngModel type="text" id="fname" name="fname"><br><br>
</form>

rc某些组件的组件是:

<div>
//...some html
<input ngModel name="someComponent" type="file" class="d-none" (change)="onUploadImage()" />
</div>

当我尝试检查onSubmit上发送的数据时,我只从fname获得数据。这意味着我无法从rc某个组件内部的输入中获取数据。我该如何解决这样的问题?我应该创建类似ControlValueAccelor的东西吗?

我只想在调用onSubmit时访问输入数据(来自这个自定义组件((这样我就可以在这个.formName.value中检查它(

如果您使用FormGroup和FormControls 构建表单,这里有一个解决方案

首先,在您的子组件上,您需要用<div [formGroup]="nameOfFG">打包输入,在输入中,您需要设置属性formControl="nameOfFC'

在类中,您唯一需要做的就是提供@Input属性。在这种情况下,您需要@Input nameOfFG:FormGroup@Input nameOfFC:string。然后,在parentcomponent.html中,您需要输入这些值——nameOfFGnameOfFC。表单需要在[]中,因为您将从组件中绑定它。

<custom-component [nameOfFG]="fromGroup" nameOfFC="formControl"></custom-component>

然后,在父类中,只需使用正在使用的formControl初始化ngOnInit()中的formgroup。

如果你仍然想走另一条路,看看EventEmitter。基本上在子组件上,EventEmitter将在输入更改时被调用,即通过@Output导出,然后可以用来更改父类中的变量

<custom-component (event)="changeYourVariable()"></custom-component>

如果您有兴趣添加验证,您需要实现ControlValueAccessor接口,甚至可能实现Validator接口。

我写了一篇关于可以检查的自定义表单控件的文章。

我还创建了这个StackBlitz演示,它正是你想要的。

最新更新