我创建了一个父组件,如下所示:
<form [formGroup] = "cardForm">
<app-inputvalidator [controls] = "cardForm.get('name')"></app-inputvalidator>
</form>
父ts文件
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl,Validators } from '@angular/forms';
@Component({
selector: 'app-card-form',
templateUrl: './card-form.component.html',
styleUrls: ['./card-form.component.css']
})
export class CardFormComponent implements OnInit {
nameFormControl ;
cardForm = new FormGroup({
name: new FormControl('', [Validators.minLength(5),Validators.maxLength(25)])
});
constructor() {
}
ngOnInit(): void {
this.nameFormControl = this.cardForm.get('name');
}
}
我将nameFormControls传递给子组件,并在模板和类中访问它,如下所示:
输入验证器.ts
import { Component, OnInit, Input } from '@angular/core';
import { FormControl} from '@angular/forms';
@Component({
selector: 'app-inputvalidator',
templateUrl: './inputvalidator.component.html',
styleUrls: ['./inputvalidator.component.css']
})
export class InputvalidatorComponent implements OnInit {
@Input() controls: FormControl;
constructor() {
}
ngOnInit(): void {
}
}
输入验证器.html
<input [formControlName] = "controls"
<br>
<div>{{ controls.errors | json}}</div>
项目编译成功,没有任何错误。
我正在将controls.errors的值设置为始终为null。为什么我不能打印对象控件。名称输入框中的值更改时使用字符串插值的错误?
如果没有放入所需的验证器,则会得到null。min,maxLength验证器将在有值且该值无效的情况下返回错误,如果该值为null或空字符串,则视为有效的
检查验证器👉源