简体   繁体   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;
    }


}

In this example I can dynamically set the value of "layout" attribute.在这个例子中,我可以动态设置“layout”属性的值。 this example will do :这个例子会做:

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

BUT I want to set the name of the attribute dynamically in order to achieve this :但是我想动态设置属性的名称以实现这一点:

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

I could create 12 versions of my component.I won't.我可以创建 12 个版本的组件。我不会。 Any idea ?任何的想法 ?

There isn't really an easy way to dynamically add or remove attributes via template binding in Angular, since attributes themselves are usually supposed to be static and have their values changed instead.通过 Angular 中的模板绑定动态添加或删除属性并不是一种简单的方法,因为属性本​​身通常应该是静态的,并且它们的值会发生变化。

It's not impossible, though.不过,这并非不可能。 I would recommend folding the logic into a directive:我建议将逻辑折叠成一个指令:

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

In component:在组件中:

export class FieldComponent {

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

}

Based on this use case, however, I'd be very surprised if there wasn't better built-in functionality behavior.然而,基于这个用例,如果没有更好的内置功能行为,我会感到非常惊讶。 I would have assumed that these attributes are either actually directives (which would need to be changed via a HostBinding ) or that there's some built-in way to handle what I assume is responsiveness.我会假设这些属性实际上是指令(需要通过HostBinding更改)或者有一些内置方法来处理我假设的响应性。 It's pretty unusual to have attributes there just for styling purposes.仅出于样式目的而在那里设置属性是非常不寻常的。

The simplest I could come up with so far...到目前为止我能想到的最简单的......

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

There is another way to add attribute in component selector (angular 12).还有另一种在组件选择器中添加属性的方法(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);
    }
}

Output -输出 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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