angular6: I want my inherited component to have some propertys of the parent

Viewed 803

I have a table where every table-cell is a different instance of a component. Depending on the data (date, text, links) I'm using different components.

As these components have a lot in common I introduced a TableCellMasterComponent which is extended by all other type of table-cells.

All my components have the same host property:

@Component({
  selector: 'td[app-text-col]',
  templateUrl: './text-col.component.html',
  styleUrls: ['./text-col.component.css'],
  host: {
    "[hidden]": "col.deactivated"
  },
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TextColComponent extends TableCellMasterComponent{
}

Is it possible to somehow move this to the TableCellMasterComponent?

Also I would love to give all of them a contextmenu. But as I see it, it isn't possible to add HTML in the Master. Is that true?

Can I move the changeDetection to the Master?

2 Answers

The @Component decorator metadata is not inherited so you cannot move some things to the base class. @Input and @Output properties get inherited.

There is a solution for the host property you can use a @HostBinding instead and this will get inherited. For example your binding you can do like this:

@HostBinding('hidden') get hidden(): boolean { return col.deactivated; }

I also created a Stackblitz which solves them the only way I know how. Credit to AlesD for solving your first problem, all you needed to do to solve the issue is add @Input() onto visibility which you control in the parent element.

Your issue with a context menu is less straightforward. One option that I quickly tried to show in my stackblitz using ngx-contextmenu is done using nested components. There's a nice tutorial here

As you discovered, you have to choose between using extends, or using a nested component. In my example, I use both, but it may make the most sense to just use one or the other depending:

  • If your context menus are different and redundancy is not that big an issue, use extends, and build the context menu manually on each component
  • if the context menus are all going to be the same, I would drop the extends entirely and use a nested component. You can access the nested component using @ViewChild to gain access to the attributes you need.
  • Using both (like in my example) was used mostly for demonstrating as I don't understand the whole context of your application, but if you could abstract your cells to use a common interface or class you can pass in to the contextMenu, limiting the number of inputs, it may make sense for you.
Related