簡體   English   中英

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

[英]How to manipulate multiple directives in Angular 2

幾周前我剛剛開始使用 Angular 2,我在這里遇到了一些問題,所以我可能需要一些幫助。 問題是我想在 Ionic 2 中創建可以重用的自定義組件。 例如,如果我決定創建一個不同大小的自定義按鈕。

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

其中sm-sizerounded會將特定的 CSS 代碼注入到我的組件中。 我認為它們是屬性指令,但我仍然看不到如何操作它。 有人可以幫我理解嗎?

您應該在這里使用 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

您可以使用@Input() s go get 屬性是否設置,並且您可以使用@HostBinding()將樣式或類綁定應用於宿主元素和[style.xxx] , [ngStyle] , [class.xxx][ngClass]將樣式和類應用於組件的內容:

@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;
  }
}

setter 是一種獲取有關是否在沒有值的情況下設置屬性的信息的方法

<btn-custom smSize rounded>

對比

<btn-custom smSize="50" rounded="true">
<btn-custom [smSize]="50" [rounded]="true">

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM