Angular 12 - 类型错误:无法读取 null 的属性(读取“writeValue”)
我正在创建一个通用文本输入组件,在为项目提供服务时一切正常,但在构建的项目中我收到此错误:
类型错误:无法读取 null 的属性(读取“writeValue”)
HTML:
<div class="p-field">
<label>{{label}} <span class="p-error">{{checkRequired(ngControl.control) ? '*' : ''}}</span></label>
<input class="full-width" [type]="type" pInputText [formControl]="ngControl.control">
<small *ngIf="ngControl.control.touched && ngControl.control.errors?.required" class="p-error">{{label}} is required</small>
<small *ngIf="ngControl.control.errors?.minlength" class="p-error">
{{label}} must be at least {{ngControl.control.errors.minlength['requiredLength']}}
</small>
<small *ngIf="ngControl.control.errors?.maxlength" class="p-error">
{{label}} must be at most {{ngControl.control.errors.maxlength['requiredLength']}}
</small>
<small *ngIf="ngControl.control.errors?.email" class="p-error">
This email is not valid
</small>
<small *ngIf="ngControl.control.errors?.isMatching" class="p-error">Passwords do not match</small>
</div>
Run Code Online (Sandbox Code Playgroud)
组件.ts
import { Component, Input, OnInit, Self } from '@angular/core';
import {AbstractControl, …Run Code Online (Sandbox Code Playgroud) 我需要将表单从父组件注入到子组件中,以便能够验证子组件输入,如下所示:
<form #formReference="ngForm">
<child-component></child-component>
<child-component></child-component>
<child-component></child-component>
<p>{{formReference.form.valid}}</p>
</form>
Run Code Online (Sandbox Code Playgroud)
现在我已经在子组件上添加了这个提供程序,使其使用父表单并且工作正常
@Component({
selector: 'app-child-component',
templateUrl: './child-component.component.html',
styleUrls: ['./child-component.component.scss'],
viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ]
})
Run Code Online (Sandbox Code Playgroud)
但是,我仍然需要能够像以前一样在没有表单的情况下使用子组件。有没有办法让这个提供者可选?目前,如果在没有表单包装的情况下使用我的子组件,我会收到错误
ERROR NullInjectorError: R3InjectorError(CustomModule)[NgForm -> NgForm -> NgForm -> NgForm -> NgForm]
Run Code Online (Sandbox Code Playgroud)
谢谢你的时间!