根据给定属性更改组件行为

Change Component behaviour based on given attribute

如何在 Angular 中创建一个根据给定属性更改行为的组件?

示例:

<my-comp [data]="data"></my-comp>

对比

<my-comp [data]="data" sortable> </my-comp>

<my-comp> 只是一个 Component 将数据显示为 html 列表。如果在不使用 @Input() 的情况下设置了属性 sortable,是否可以检查 MyComponent? 我是否必须定义一个 Directive 或者我能否以某种方式访问​​该属性?

类似于:

private _sortable:boolean = false;
@Input() sortable(val) {
  if(val) {
    this._sortable = true;
  }
}

我怀疑你可以使用 @Attribute 装饰器

my.component.ts

@Component({
  selector: 'my-comp',
  template: `
    <h1>Comp hasSortable {{ hasSortable }}</h1>
  `
})
export class MyComponent {
  hasSortable: boolean;
  constructor(@Attribute('sortable') private sortable: any) {
    this.hasSortable = sortable !== null;
  }
}

parent.component.html

<my-comp></my-comp>           // Prints "Child hasSortable false"
<my-comp sortable></my-comp>  // Prints "Child hasSortable true"

Plunker Example