【问题标题】:What is the difference between class and [class] in angular htmlangular html中的class和[class]有什么区别
【发布时间】:2020-12-01 03:11:03
【问题描述】:

寻找有关角度文件夹结构的良好做法我偶然发现了这段代码:

content-layout.component.html:

<div [class]="theme">
  <div class="mat-app-background">
    <app-nav></app-nav>

      <div class="container">
        <router-outlet></router-outlet>
      </div>

    <app-footer></app-footer>
  </div>
</div>

据我了解,class 标签用于将此组件 HTML 与 CSS 类绑定。 但是方括号引起了我的注意,[class] 和用于 css 绑定的类之间有什么真正的区别吗?我无法自己搜索正确的搜索词/功能名称

【问题讨论】:

    标签: html css angular components styles


    【解决方案1】:

    括号[] 表示该值是组件中的一个属性,因此不是说将类theme 应用于元素,而是在组件中查找属性theme 并使用存储的任何内容在那里。

    class="theme" // apply class theme

        // Component
        public theme = 'theme';
    
        // HTML
        [class]="theme" // use what's stored in property "theme"
    
        or
    
        [class]="'theme'" // use string 'theme'
    

    【讨论】:

    • 为了进一步扩展这个答案,Angular 将其称为“绑定”。方括号本身表示单向绑定,但也可以进行双向绑定。请参阅此处了解更多信息:angular.io/guide/binding-syntax
    【解决方案2】:

    [] 是一种将数据绑定到 ts 和 HTML 的方式,所以在这种情况下,theme 是一个变量,而另一边 container 是一个直接属性

    【讨论】:

      【解决方案3】:

      你对class的理解是对的,来到[class],根据值,class将应用于那个元素。如果该值为 true 或某个值,则该类将应用于该元素,否则它将忽略该类。所以基本上你是在使用一个特定的类来实现某些功能,而不是把它用于另一个

      eg: &lt;div [class.classOne]="true"&gt;&lt;/div&gt; // 现在 div 元素将具有 classOne 类,因为结果为 true 或某个值。

      更好地理解类的参考: https://angular.io/api/common/NgClass,

      Difference between [ngClass] vs [class] binding

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-05
        • 1970-01-01
        • 1970-01-01
        • 2013-02-15
        • 2020-08-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多