Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend component with Input/Output

Tags:

angular

Is it possible to extend a component in Angular 2 and still use the inputs and outputs in the parent?

export class Book {
  @Input() name;
}

export class EBook extends Book {
  @Input() downloadUrl;
  @Input() size;
}

When I try to extend a component everything inside the class works except the code that need attributes/decorators, like inputs and outputs. I made a plunker that illustrates the problem: http://plnkr.co/edit/cfTKgScbaXMmEMoGY0zr

Book is a base component with one input/output Name.

EBook inherits from Book and adds input/output DownloadUrl, Size.

As you can see in the plunker, EBook doesn't get a name since the input is defined in Book and not in EBook

like image 914
Abris Avatar asked Nov 30 '15 11:11

Abris


People also ask

Can a component extend another component?

Using class inheritance in TypeScript, you can declare a base component that contains common UI functionality and use it to extend any standard component you'd like.

Is there inheritance in angular?

Inheritance with Angular ComponentsWe can create a “parent” component with common properties/functions, followed by a child component that “extends” the parent. The child will inherit the parent's properties and functions but will have its own template, stylesheet and test file.

What does Extends do in angular?

Extends the destination object dst by copying own enumerable properties from the src object(s) to dst . You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular. extend({}, object1, object2) .

Where does the component metadata inherit from?

Metadata and Decorators are not inherited But there is an exception, @Input and @Output decorators are passed down to the child components. The two properties ( @Input() input , @Output() output ) in ComponentA will be visible to ComponentB .


2 Answers

As for the current version of Angular (7.0.1 while writing this), your use case is perfectly supported. And the issue linked by Oliver has been closed.

Created an example Stackblitz (only highlighting input decorators): https://stackblitz.com/edit/angular-fepmtp

like image 78
Slartibartfast Avatar answered Sep 17 '22 15:09

Slartibartfast


as for rc4, input decorators are only inherited if the sub-class has no input decorators itself. otherwise you have to copy all the declarations.

its a known issue, you can follow up here: https://github.com/angular/angular/issues/5415

like image 23
Oliver Renner Avatar answered Sep 20 '22 15:09

Oliver Renner