Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 使用参数作为角度视图中的对象属性_Angular - Fatal编程技术网

Angular 使用参数作为角度视图中的对象属性

Angular 使用参数作为角度视图中的对象属性,angular,Angular,有没有办法将字符串转换为angular中的对象属性?例如: getErrorMessage(error_type) { return this.userForm.controls.{error_type}.hasError('required') ? 'You must enter a value' : ''; } getErrorMesssage('email'); 该函数的工作原理如下 return this.userForm.controls.email.hasError('r

有没有办法将字符串转换为angular中的对象属性?例如:

getErrorMessage(error_type) {
    return this.userForm.controls.{error_type}.hasError('required') ? 'You must enter a value' : '';
}

getErrorMesssage('email');
该函数的工作原理如下

return this.userForm.controls.email.hasError('required') ? 'You must enter a value' : '';
您可以使用
get()
函数:

getErrorMessage(controlName: string) {
    return this.userForm.get(controlName).hasError('required') ? 'You must enter a value' : '';
}

唯一的问题是,您希望传递的是控件名,而不是错误类型,我可以从变量命名中看到这一点。

一般来说,您可以使用括号表示法访问对象属性:

const thing={email:'foo@bar.com };
console.log(东西['email']);//印刷品foo@bar.com'

方括号,不卷曲。

返回此.userForm.controls[错误类型].hasrerror('required')
getErrorMessage(error_type) {
  return this.userForm.controls[error_type].hasError('required') ? 'You must enter a value' : '';
}