angular创建可重用的输入组件



我正在创建一个具有验证器的可重用文本组件

export class CompInputComponent implements OnInit{
@Input() controlFormGroup: FormGroup;
@Input() controlLabel: string;
@Input() controlPlaceHolder: string;
@Input() controlName: string;
@Input() errorMessage: string;
private _isRequired = false;
@Input()
get isRequired(): boolean {
return this._isRequired;
}
set isRequired(val: boolean) {
this._isRequired = coerceBooleanProperty(val);
}
@Output() onComponentReady: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();

constructor(private fb: FormBuilder) { }

ngOnInit(){
console.log(this.isRequired);
if(this.isRequired){
console.log(this.isRequired);
this.controlFormGroup.addControl(this.controlName, new FormControl('', Validators.required));
}else{
this.controlFormGroup.addControl(this.controlName, new FormControl(''));
}
this.onComponentReady.emit(this.controlFormGroup);
}
}
<div [formGroup]="controlFormGroup">
<mat-form-field appearance="outline">
<mat-label>{{controlLabel}}</mat-label>
<input matInput [placeholder]="controlPlaceHolder" [formControlName]="controlName" />
<mat-error *ngIf="controlFormGroup.controls.controlName.hasError('required')">">
<span [innerHTML]="errorMessage"></span>
</mat-error>
</mat-form-field>
</div>

我的问题是我不能设置垫子错误。我有以下错误:

core.js:5967 ERROR TypeError:无法读取未定义的属性'hasError在CompInputComponent_Template

控件的名称不是硬的,而是动态的

这应该工作,你是动态创建你的表单控件,这意味着他们不存在的开始。您需要检查表单控件是否已创建。

export class CompInputComponent implements OnInit{
@Input() controlFormGroup: FormGroup;
@Input() controlLabel: string;
@Input() controlPlaceHolder: string;
@Input() controlName: string;
@Input() errorMessage: string;
private _isRequired = false;

@Input()
get isRequired(): boolean {
return this._isRequired;
}
set isRequired(val: boolean) {
this._isRequired = coerceBooleanProperty(val);
}

@Output() onComponentReady: EventEmitter<FormGroup> = new EventEmitter<FormGroup>();

constructor(private fb: FormBuilder) { }

ngOnInit(){
console.log(this.isRequired);
if(this.isRequired){
console.log(this.isRequired);

this.controlFormGroup.addControl(this.controlName, new FormControl('', Validators.required));
}else{
this.controlFormGroup.addControl(this.controlName, new FormControl(''));
}

this.onComponentReady.emit(this.controlFormGroup);
}
}

<div [formGroup]="controlFormGroup">
<mat-form-field appearance="outline">
<mat-label>{{controlLabel}}</mat-label>
<input matInput [placeholder]="controlPlaceHolder" [formControlName]="controlName" />
<mat-error *ngIf="!!controlFormGroup.controls.controlName && controlFormGroup.controls.controlName.hasError('required')">">
<span [innerHTML]="errorMessage"></span>
</mat-error>
</mat-form-field>
</div>

最新更新