微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

angular改变css

在Angular中改变CSS样式可以使用ngStyle或者ngClass。ngStyle用于修改元素的内联样式,ngClass用于给元素附加或移除CSS类。

// ngStyle
Hello World
// ngClass
Click Me

angular改变css

ngStyle中需要传入一个包含键值对的对象,每个键代表一个样式属性,每个值代表对应的属性值。ngClass中可以传入一个包含多个键值对的对象,每个键代表一个CSS类名,每个值代表是否应该附加该类名。

// 在组件中控制ngStyle

@Component({
  selector: 'app-root',template: `
    
    
    
Hello World
`,}) export class AppComponent { styleObj = { 'font-size': '14px','color': 'red' }; increaseFontSize() { const currentSize = parseInt(this.styleObj['font-size']); this.styleObj['font-size'] = currentSize + 1 + 'px'; } changeColor() { this.styleObj.color = 'blue'; } }

ngClass中也可以通过组件中的数据来控制是否附加某个CSS类。

// 在组件中控制ngClass

@Component({
  selector: 'app-root',template: `
    
    
Click Me
`,}) export class AppComponent { classObj = { 'btn': true,'btn-primary': true }; isPrimary = true; togglePrimary() { this.isPrimary = !this.isPrimary; this.classObj['btn-primary'] = this.isPrimary; } }

通过ngStyle和ngClass,我们可以方便地在Angular中修改CSS样式,使得页面可以动态地响应用户操作并进行样式上的变化。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。