繁体   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