我创建了一个父组件,如下所示:
<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 的值设置为始终为空。为什么当名称输入框中的值发生变化时,我不能使用字符串插值打印对象 controls.errors?