Angular 表单:等效于 Reactive Forms 的构造函数 ngForm 注入?
Angular form: Equivalent of constructor ngForm injection for Reactive Forms?
我正在尝试构建一个组件来显示如下验证错误消息:
<form>
<input ngModel name="firstname" required>
<validation-error for="firstname"></validation-error>
</form>
<validation-error>
组件对于模板驱动表单来说非常简单,因为我们可以在构造函数中注入 NgFrom
并使用 ngFrom.form.get(myControlName)
找到控件及其状态:
@Component({
selector: 'validation-error',
template: `{{errorText}}`,
styles: [`:host { display:block; color:red; }`]
})
export class ValidationErrorComponent {
@Input() for: string; // name of input element
constructor(
@Optional() private ngForm: NgForm // This works for Template forms only.
) { }
get errorText() : string {
const formControl = <FormControl>this.ngForm.form.get(this.for);
return (formControl.errors) ? JSON.stringify(formControl.errors) : "[no error]";
}
}
但是 NgForm
似乎只为模板表单注入。是否有响应式表单的等效提供程序可以访问封闭的 FormGroup
?
不注入 ngForm,而是使用 ControlContainer 访问 FormControls。
控件容器
A base class for directives that contain multiple registered instances of NgControl.
@Component({
selector: 'validation-error',
template: `{{errorText}}`,
styles: [`:host { display:block; color:red; }`]
})
export class ValidationErrorComponent {
@Input() for: string; // name of input element
constructor(
@Optional() private control: ControlContainer
) { }
get errorText() : string {
const formControl = <FormControl>(this.control as any).form.get(this.for);
return (formControl.errors) ? JSON.stringify(formControl.errors) : "[no error]";
}
}
我正在尝试构建一个组件来显示如下验证错误消息:
<form>
<input ngModel name="firstname" required>
<validation-error for="firstname"></validation-error>
</form>
<validation-error>
组件对于模板驱动表单来说非常简单,因为我们可以在构造函数中注入 NgFrom
并使用 ngFrom.form.get(myControlName)
找到控件及其状态:
@Component({
selector: 'validation-error',
template: `{{errorText}}`,
styles: [`:host { display:block; color:red; }`]
})
export class ValidationErrorComponent {
@Input() for: string; // name of input element
constructor(
@Optional() private ngForm: NgForm // This works for Template forms only.
) { }
get errorText() : string {
const formControl = <FormControl>this.ngForm.form.get(this.for);
return (formControl.errors) ? JSON.stringify(formControl.errors) : "[no error]";
}
}
但是 NgForm
似乎只为模板表单注入。是否有响应式表单的等效提供程序可以访问封闭的 FormGroup
?
不注入 ngForm,而是使用 ControlContainer 访问 FormControls。
控件容器
A base class for directives that contain multiple registered instances of NgControl.
@Component({
selector: 'validation-error',
template: `{{errorText}}`,
styles: [`:host { display:block; color:red; }`]
})
export class ValidationErrorComponent {
@Input() for: string; // name of input element
constructor(
@Optional() private control: ControlContainer
) { }
get errorText() : string {
const formControl = <FormControl>(this.control as any).form.get(this.for);
return (formControl.errors) ? JSON.stringify(formControl.errors) : "[no error]";
}
}