我正在尝试将子组件中的 ngModel 传递给公共组件显示错误。
它给出了错误。 模板解析错误:没有NgControl的提供程序。
任何人都可以查看代码,让我知道我错过了什么。
父组件
<div>
<h2>Hello {{name}}</h2>
<form #countryForm="ngForm">
<div class="form-group row">
<label for="txtCountryName" class="col-sm-3 col-form-label">Country Name</label>
<div class="col-sm-9">
<input type="text" [(ngModel)]="name" ngModel #countryName="ngModel" name="name" class="form-control" id="txtCountryName" placeholder="Country Name" required minlength="5" maxlength="15">
<app-error-message [formControl]="countryName"></app-error-message>
</div>
</div>
</form>
</div>
子组件
@Component({
selector: 'app-error-message',
template: `<ng-container *ngIf="formControl">
<div [hidden]="(formControl.valid || formControl.pristine) && (formControl.errors == null || formControl.errors.invalid == null)" class="alert alert-danger">
{{GetValidationMessage()}}
</div>
</ng-container>`
})
export class ErrorMessageComponent {
@Input() public formControl: any = null;
public GetValidationMessage() {
let errorMessage: string = "";
if (this.formControl.errors) {
if (this.formControl.dirty || this.formControl.touched) {
if (this.formControl.errors.required != null) {
errorMessage = "This field is required.";
}
if (this.formControl.errors.minlength != null) {
errorMessage += "This field must be 8 characters long, we need another " + (this.formControl.errors.minlength.requiredLength - this.formControl.errors.minlength.actualLength) + " characters";
}
}
if (this.formControl.errors.invalid != null) {
errorMessage += this.formControl.errors.errorMessage;
}
}
return errorMessage;
}
}
答案 0 :(得分:2)
您应该使用@Input
的其他名称与不需要NgControlStatus
提供商https://github.com/angular/angular/blob/3ce3b4d2afdc5198a9a5a9432db1f88e2e5d1972/packages/forms/src/directives/ng_control_status.ts#L56的内置指令NgControl
相交
为此,您可以完全替换属性名称
错误-message.component.ts 强>
@Input() public control: any = null;
<强> parent.html 强>
<app-error-message [control]="countryName"></app-error-message>
<强> Forked Plunker 强>
或使用@Input
错误-message.component.ts 强>
@Input('control') public formControl: any = null;
<强> parent.html 强>
<app-error-message [control]="countryName"></app-error-message>
<强> Forked Plunker 强>
答案 1 :(得分:1)
尝试访问父组件中的本地模板引用变量#countryName
。通过@ViewChild
然后将属性public countryName: any
设置为等于本地模板变量。
//父组件
export class ParentComp implements AfterViewInIt{
@ViewChild('add_template_reference_variable_here') countryNameRef;
public countryName: any;
ngAfterViewInit(): void {
this.countryName = this.countryNameRef;
}
}
然后将新变量绑定到[formControl]="countryName"
//父Html模板
<app-error-message [formControl]="countryName"></app-error-message>