1

how do I create a component in Angular which changes the behaviour based on the given attribute?

Example:

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

vs

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

<my-comp> is just a Component witch shows the data as a html list. Is it possible to check in the MyComponent if the attribute sortable is set without using @Input()? Do I have to define a Directive or can I somehow access the attribute?

2 Answers 2

2

I suspect you can do by using @Attribute decorator

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

Sign up to request clarification or add additional context in comments.

Comments

0

Something like:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.