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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 17:07:15

问题


I am creating a reactive form in angular. To synchronize the FormControl object from your typescript file to control of form in html file, you need to use formControlName directive. This is done as follows:

formControlName="xyz"

where xyz is the key of FormControl object defined in typescript file. But in this case, xyz is treated as a string and will not get evaluated. So my doubt is that, since xyz is a key to FormControl object, so it should be evaluated and must used with square brackets like

[formControlName]="xyz"

I am satisfied with the way FormGroup is used because it is used with square brackets like:

[FormGroup] = "abc"

where abc is an object reference to FormGroup object defined in typescript file of the component.

So please explain why formControlName is not used with a square bracket?


回答1:


This behaviour is not limited for formControlName but for all angular input/attribute properties. It boils down to what you wanted to achieve and how your angular style guide is defined.

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"



来源:https://stackoverflow.com/questions/58262752/in-reactive-forms-of-angular-why-the-parameter-passed-in-formcontrolname-is-pas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!