在 angular 的反应式形式中,为什么传入 formControlName 的参数是作为字符串传递的?

In reactive forms of angular, why the parameter passed in formControlName is passed as a string?

我正在 angular 中创建反应形式。要将打字稿文件中的 FormControl 对象同步到 html 文件中的表单控件,您需要使用 formControlName 指令。这是按如下方式完成的:

formControlName="xyz"

其中 xyz 是 typescript 文件中定义的 FormControl 对象的键。 但在这种情况下,xyz 被视为一个字符串,不会被评估。所以我的疑问是,因为 xyz 是 FormControl 对象的键,所以它应该被评估并且必须与方括号一起使用,如

[formControlName]="xyz"

我对 FormGroup 的使用方式很满意,因为它与方括号一起使用,例如:

[FormGroup] = "abc"

其中 abc 是对组件的打字稿文件中定义的 FormGroup 对象的对象引用。

所以请解释为什么 formControlName 不与方括号一起使用?

此行为不仅限于 formControlName,而且适用于所有 angular input/attribute 属性。它归结为您想要实现的目标以及您的 angular 风格指南是如何定义的。

1. With brackets []: When you expect angular to evaluate the input passed to formControlName use []. In the below example angular will treat name as a property of your typescript class and resolve for its value. Eg: [formControlName] = "name"

2. Without brackets: When you expect angular to pass the value just as string to formControlName you dont use []. In the below example name is string also states you are sure that the name of the formcontrol doesn't change dynamically. Eg: formControlName = "name"