首页 > 解决方案 > 绑定到Angular 12中div的未知属性

问题描述

我试图通过将属性绑定到组件中的属性来切换属性的值。

<div class="app-container" [data-theme]="theme">
  <router-outlet></router-outlet>
</div>
import { Component } from '@angular/core';

import { ThemeService } from './common/_services';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  theme = 'dark';

  constructor(private themeService: ThemeService) {
    this.themeService.isDark.subscribe(x => {
      this.theme = x ? 'dark' : 'light';
    });
  }
}

通过设置dark或属性,使用不同lightdata-theme颜色。所以我只需要一种切换值的方法。

如果我尝试使用上面的代码,我会得到:

错误:src/app/app.component.html:1:28 - 错误 NG8002:无法绑定到“数据主题”,因为它不是“div”的已知属性。

有什么方法可以轻松地将我的属性绑定到模板?为什么我会收到这个错误?

标签: angulartypescript

解决方案


我只需要使用属性绑定,如下所示:

[attr.data-theme]="theme"

推荐阅读