首页 > 解决方案 > 制作单选按钮并在任何组件中使用它

问题描述

我想使用单选按钮并在具有不同样式的不同组件中使用它,而无需重写 html 和 css。而且我希望他们在我切换每个时改变他们的风格

首先,我使用 html 和一些 css 将单选按钮作为单独组件中的一个组件

<div class="list-item" (click)="check()">
  <span class="list-item-text">
    {{data.value}}
  </span>
  <div class="inputs">
    <span class="box">
      <span class="inner-box" [class.fill]="fill"></span>
    </span>
  </div>
</div>

并使用 ts 来制作切换功能

export class ProductAllFilterComponent implements OnInit {
public Categories =[];

  constructor(
    private categoryService:CategoryService,
    private _router:Router) { 
      this.categoryService.getCategories().subscribe((response:any)=>{
        this.Categories = response.data;
      });
  }
active = 1;
  ngOnInit() {
  }

  goToLink(link) {
    this._router.navigate([link])
  }
  // route back to home

  activeSection(index) {
    this.active = index;
  }
}

我怎样才能把它变成可重用的组件并添加不同的样式而不改变它在所有其他组件中的样式。

标签: angularangular8

解决方案


解决方案可能是将 @Input() 和 ngStyle 添加到您的组件中。例如,如果您希望您的按钮在某些时候变为红色,您可以在 TS 中使用:

@Input() color: string;
defaultColor: //your default color

在 HTML 中:

<span class="box" [ngStyle]="{'background: color ? color : defaultColor'}"> ...

然后你必须使用它的选择器在另一个组件中调用你的组件,例如:

<app-custom-checkbox color="#ff0000"></app-custom-checkbox>

推荐阅读