我正在构建一个应用程序
与组件 FormComponent。
在里面我使用 Angular Core 的反应式表单模块
并创建一个自定义验证器。
该函数正在使用 this 调用另一个函数 - 因为我认为它将引用 FormComponent,
但它指的是“未定义”
(?)
onInit 中的代码定义了 FormGroup 和 FormControl
并在其外部定义函数
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
formInsurance:FormGroup;
private id:FormControl;
constructor(){}
ngOnInit() {
this.id = new FormControl('',[
Validators.required,
Validators.minLength(3),
Validators.maxLength(10),
Validators.pattern('^[0-9]+(-[0-9]+)+$|^[0-9]+$'),
this.foo
]);
this.formInsurance = new FormGroup({
id:this.id
})
}
foo(control:FormControl){
this.boo();
if(control.value){
return {
objToReturn: {
returned: name
}
};
}
return null
}
boo(){
console.log('boo')
}
}
从 FormControl 中调用时 foo 方法中的上下文不引用 FormComponent。
您可以执行以下操作来修复此行为bind自己设置上下文:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {
formInsurance:FormGroup;
private id:FormControl;
constructor(){}
ngOnInit() {
const id = new FormControl('',[
Validators.required,
Validators.minLength(3),
Validators.maxLength(10),
Validators.pattern('^[0-9]+(-[0-9]+)+$|^[0-9]+$'),
this.foo.bind(this)
]);
this.id = id;
this.formInsurance = new FormGroup({
id
})
}
foo(control:FormControl) {
this.boo();
if(control.value){
return {
objToReturn: {
returned: name
}
};
}
return null
}
boo(){
console.log('boo')
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)