【发布时间】:2019-09-15 15:17:44
【问题描述】:
我正在使用具有以下代码的自定义组件(自定义文本)
@Component({
selector: 'custom-text, [custom-text]',
templateUrl: './custom-text.template.html',
styleUrls: ['./custom-text.component.scss']
})
export class CustomTextComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}
Inside the custom-text.template.html
<mat-form-field>
<input matInput
id="controlid"
name="controlname"
maxlength="8"
[(ngModel)]="value">
</mat-form-field>
当我将此控件包含在另一个组件的表单(模板驱动)中时。
<form #someForm="ngForm">
<div custom-text></div>
</form>
or
<form #someForm="ngForm">
<custom-text></custom-text>
</form>
我无法使用 someForm.controls['controlId'] 获取控件实例
我做错了什么。
【问题讨论】:
-
来自控件的自定义必须实现 ControlValueAccessor,参见例如stackoverflow.com/questions/40009149/…
-
@Eliseo 感谢您帮助我解决这个问题,但是,当我将它与 mat-form-field 一起使用时,它无法按预期工作,父表单不会将此控件视为它。
-
我在下面介绍了如何根据输入垫制作自定义控件验证器
-
我添加了另一个不使用自定义表单控件的响应。在 stackblitz 中,您有两种选择
标签: angular angular7 angular-forms angular-template-form