【问题标题】:attribute directive syntax with and without square bracket [] [duplicate]带和不带方括号 [] 的属性指令语法 [重复]
【发布时间】:2019-12-27 09:44:11
【问题描述】:

属性指令应该使用具有selector:'[myDirective]' 语法的选择器,然后在<p myDirective ></p>' 等模板中使用。我还看到 ngClass 是一个属性指令,用法类似于[ngClass]="'class1 class2'"。我想知道什么时候使用方括号,什么时候不使用。它是否与指令选择器和同名属性绑定之间的某种关系有关?

【问题讨论】:

    标签: angular


    【解决方案1】:

    当需要计算表达式时使用方括号。 ngClass 可以不带括号使用。下面的代码会将 class1 和 class2 视为普通字符串。

    ngClass="class1 class2"
    

    【讨论】:

    • 这里为什么不用单引号?
    • 由于 ngClass 没有方括号 angular 会将 class1 class2 视为普通字符串。 Ang 如果有括号,它会将它们视为变量。
    【解决方案2】:

    我认为这取决于您使用的实体类型。 在选择器中,如果你在一个组件上工作,你可以写:

    selector:'[myComponent]'  => <div myComponent></div>
    

    selector:'myComponent'   => <myComponent></myComponent>
    

    属性绑定可以这么写

    <div [title]="theTitleProperty"></div>
    

    这会将 html 标题属性绑定到组件属性 theTitleProperty 的值。 (alt div title="{{theTitleProperty}}") 而

    <div title="theTitleProperty"></div>
    

    将为标题赋予值'theTitleProperty''

    ngClass 的替代品可以是

    <div [class]="theClassProperty"></div>
    

    然后是组件的@Inputs。 任何组件都可能有一个@Input,你可以将它与两个括号一起使用 如果你有一个带有 @Input() aText:string; 的组件 你可以这样使用它:

    <my-component [aText]="myTextProperty"></div>
    

    它会将控制属性 myTextProperty 发送到组件@Input 但是如果你这样写

    <my-component aText="myTextProperty"></div> 
    

    它会将 myTextProperty 发送到组件中。

    希望对你有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-29
      • 1970-01-01
      • 2014-11-26
      • 2011-11-27
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      相关资源
      最近更新 更多