在子组件中传递ngModel以进行常见错误处理

时间:2017-12-08 19:36:06

标签: angular angular5

我正在尝试将子组件中的 ngModel 传递给公共组件显示错误。

它给出了错误。 模板解析错误:没有NgControl的提供程序

任何人都可以查看代码,让我知道我错过了什么。

Plunker

父组件

      <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;
}

}

2 个答案:

答案 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>