如何在Angular 2中操作多个指令

时间:2017-01-27 16:44:29

标签: angular ionic2

几周前我刚刚开始使用Angular 2,我在这里遇到了一些问题,所以我可能需要一些帮助。问题是我想在Ionic 2中创建可重复使用的自定义组件。例如,如果我决定创建一个不同大小的自定义按钮。

<btn-custom sm-size rounded> </btn-custom>

sm-sizerounded会将特定的CSS代码注入我的组件。我认为它们是属性指令,但我仍然无法看到我如何操纵它。有人可以帮我理解吗?

2 个答案:

答案 0 :(得分:1)

您应该在此处使用ngStyle指令,告诉组件要应用的其他样式。

https://angular.io/docs/ts/latest/api/common/index/NgStyle-directive.html https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngStyle

使用Style指令可以注入样式。

如果你有预定义的类,那么ngClass会运行得最好,看起来就像你需要的那样:

<btn-custom [ngClass]="{'sm-size rounded' : true}">...</btn-custom>

https://angular.io/docs/ts/latest/api/common/index/NgClass-directive.html

本指南将有所帮助:

https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngClass

答案 1 :(得分:0)

您可以使用os.mkdir来获取是否设置了属性,并且可以使用@Input()将样式或类绑定应用于主机元素和@HostBinding(),{{1 }},[style.xxx][ngStyle]将样式和类应用于组件的内容:

[class.xxx]

setter是一种获取有关属性是否设置为没有值

的信息的方法
[ngClass]

vs

@Component({
  template: `
<button [style.with.px]="smSize ? 250 : 150">click me</button>
<!-- or -->
<button [ngClass]="smSize ? 'big' : 'small'">click me</button>
})
class ButtonCustom {

  private _smSize:boolean;

  get isSmSize:boolean() {
    return this._smSize;
  }

  @Input() 
  set smSize(value:any) {
    this._smSize = value != 'false'; // treat everything as `true` except `'false'`
  }

  @HostBinding('style.border-radius')
  borderRadius:number = 0;

  private _rounded:boolean;

  get isRounded:boolean() {
    return this._rounded;
  }
  @Input() 
  set rounded(value:any) {
    this._rounded = value != 'false'; // treat everything as `true` except `'false'`
    this.borderRadius = this._rounded ? 3 : 0;
  }
}