gpt4 book ai didi

Angular:从指令访问 FormControl

转载 作者:搜寻专家 更新时间:2023-10-30 21:35:12 26 4
gpt4 key购买 nike

我想通过自定义指令将验证器动态添加到我的 FormControl。

@Directive({
selector: "[idNumber]",
})
export class IdNumberDirective implements OnInit {

constructor(private formControl: FormControl) { }

ngOnInit() {
this.addValidators(this.formControl);
}

addValidators(formControl: FormControl) {
formControl.setValidators(Validators.compose(
[Validators.required,
Validators.minLength(3),
Validators.maxLength(8)
]
));
}



<mat-form-field>
<mat-label>{{label}}</mat-label>
<input matInput
[formControl]="idNumberFormControl"
[placeholder]="placeholder"
</mat-form-field>


我不需要引用 nativeElement(通过 ElementRef)。
我想引用 formControl...
...并这样使用它:

// HTML with my custom directive 'idNumber' ////////
<custom-input-string
idNumber
[name]="'idNumber'"
[label]="Id Number"
[placeholder]="">
</custom-input-string>

// TS ////////
@ViewChild(CustomInputStringComponent) child: CustomInputStringComponent;

ngAfterViewInit() {
setTimeout(() => {
this.child.insertIntoForm(this.signupForm);
}, 0);
}


有什么想法吗?
谢谢大家。

最佳答案

这是一个使用指令将验证器附加到表单控件的示例。

Stackblitz

请注意,使用它会导致丢失所有以前的验证器。

constructor(
// Get the control directive
private control: NgControl
) { }
ngOnInit() {
const abstractControl = this.control.control;
abstractControl && abstractControl.setValidators([Validators.required]);
}

关于Angular:从指令访问 FormControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52366384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com