簡體   English   中英

在組件選擇器上動態添加/更改屬性

[英]Dynamically add/change attribute on component selector

@Component({
    selector: 'ion-col',
    templateUrl: 'components-field.html'
})

export class FieldComponent {
    @HostBinding('attr.layout')
    layout = '¯\_(ツ)_/¯';
    element: any;
    constructor() {
        console.log('Hello ComponentsFieldComponent Component');
    }

    setElement(element) {
        this.element = element;
    }


}

在這個例子中,我可以動態設置“layout”屬性的值。 這個例子會做:

<ion-col layout="¯\_(ツ)_/¯"></ion-col>

但是我想動態設置屬性的名稱以實現這一點:

<ion-col col-3></ion-col>
<ion-col col-5></ion-col>
<ion-col col-12></ion-col>

我可以創建 12 個版本的組件。我不會。 任何的想法 ?

通過 Angular 中的模板綁定動態添加或刪除屬性並不是一種簡單的方法,因為屬性本​​身通常應該是靜態的,並且它們的值會發生變化。

不過,這並非不可能。 我建議將邏輯折疊成一個指令:

@Directive({
   selector: '[colThing]'
})
export class ColThingDirective {

  @Input('colThing') 
  set colCriteria(value) {
   this.doLogicToChangeAttributes(value);
  }

  public attributeList = ['col-5', 'col-3'];

  constructor(private _r: Renderer2, private el: ElementRef) {}

  doLogicToChangeAttributes(value) {
    if (value === 'col-5-criteria') {
      this.removeAttributes();
      this._r.setAttribute(this.el.nativeElement, 'col-5', '');
    }

  }

  removeAttributes() {
    this.attributeList.forEach(s => this._r.removeAttribute(this.el.nativeElement, s));
  }
}

在組件中:

export class FieldComponent {

  @HostBinding('[ColThingDirective]') someCriteriaToChangeAttribute; // <--
 @Input to directive

}

然而,基於這個用例,如果沒有更好的內置功能行為,我會感到非常驚訝。 我會假設這些屬性實際上是指令(需要通過HostBinding更改)或者有一些內置方法來處理我假設的響應性。 僅出於樣式目的而在那里設置屬性是非常不尋常的。

到目前為止我能想到的最簡單的......

<ion-col [attr.col-12]="myValue === 'col-12' ? '' : null"
         [attr.col-6]="myValue === 'col-6' ? '' : null">

還有另一種在組件選擇器中添加屬性的方法(angular 12)。

import {Component, ViewEncapsulation, ElementRef} from '@angular/core';

@Component({
  selector: 'user',
  templateUrl: './user.html',
  styleUrls: ['./user.scss'],
  encapsulation: ViewEncapsulation.None
})

export class User {
    constructor(private elementRef: ElementRef) { }

    ngOnInit(): void {
        let value = 'demo'; // value can be static or dynamic
        this.elementRef.nativeElement.setAttribute('key', value);
    }
}

輸出 -

<user key="demo">...</user>

暫無
暫無

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

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