带或不带括号的formControlName?

Arm*_*ndo 12 angular2-forms angular

使用formControlName内部括号和没有括号之间有什么区别?在动态表单中,教程formcontrolname在括号内使用

[formControlName]="dyncontrol.key"
Run Code Online (Sandbox Code Playgroud)

但是在其他教程中我没有看到它

formControlName="name"
Run Code Online (Sandbox Code Playgroud)

Pau*_*tha 8

这是来自模板语法文档:

记住括号

括号告诉Angular评估模板表达式.如果我们忘记括号,Angular会将字符串视为常量并使用该字符串初始化目标属性.它没有评估字符串!

不要犯下列错误:

<!-- ERROR: HeroDetailComponent.hero expects a
Hero object, not the string "currentHero" -->
<hero-detail hero="currentHero"></hero-detail>
Run Code Online (Sandbox Code Playgroud)

  • @cartant你在问题中看到没有括号._string_值`name`将被使用.如果它有括号,它将从组件中寻找一个名为`name`的_property_.在使用括号的问题的示例中,如果没有括号,则只使用_string_`dyncontro.key`而不是组件属性 (3认同)

小智 6

使用方括号表示该值是一个表达式,不使用方括号表示该值是一个字符串:

let a = {n: "name"};
Run Code Online (Sandbox Code Playgroud)

然后[formControlName]="a.n"是一样的formControlName="name"

所有其他 angular2 属性都具有相同的规则。