我创建了一个父组件,如下所示:<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?
1 回答
互换的青春
TA贡献1797条经验 获得超6个赞
你得到 null 因为你没有放置必需的验证器,如果有值并且该值无效,则min,maxLength验证器将返回错误,如果该值为 null 或空字符串,这将被视为有效
- 1 回答
- 0 关注
- 83 浏览
添加回答
举报
0/150
提交
取消