简体   繁体   中英

How to manipulate multiple directives in Angular 2

I've just started using Angular 2 a few weeks ago and I'm kinda stuck with something here, so I may need some help. The thing is that I would like to create custom components in Ionic 2 that could be reusable. For example, if I decide to create a custom button with different sizes.

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

Where sm-size and rounded would inject specific CSS codes into my component. I figured that they're Attribute directives, but I still can't see how I can manipulate it. Could someone please help me understanding it?

You should use the ngStyle directive here, to tell the component the additional styles to apply.

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

Using the Style directive you can inject styles.

If you have predefined classes then ngClass would work best, which looks like what you need:

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

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

This guide will help:

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

You can use @Input() s go get whether attributes are set or not, and you can use @HostBinding() to apply style or class bindings to the host element and [style.xxx] , [ngStyle] , [class.xxx] , and [ngClass] to apply styles and classes to content of your component:

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

The setters are a way to get the info about whether an attribute is set without a value

<btn-custom smSize rounded>

vs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM