Angular2 - Override Component

1,778 views
Skip to first unread message

Stephane Dion

unread,
May 30, 2016, 10:35:25 AM5/30/16
to AngularJS
It is possible to override a component with a new implementation like we can do with the services?

I want to be able to replace the template or the css of a Component.

@Component({
selector: 'foo',
template: '<span>foo</span>'
})
export class FooComponent {}

@Component({
selector: 'my-app',
template: '<foo></foo>',
directives:[FooComponent]
})
export class AppComponent {}



@Component({
selector: 'foo',
template: '<h1>foo override</h1>'
})
export class FooOverrideComponent extends FooComponent {}

//Can we inject a new implementation of component?
bootstrap(AppComponent, [(FooComponent, {useClass: FooOverrideComponent})]);

Thanks,
Stephane

Sander Elias

unread,
May 30, 2016, 9:54:23 PM5/30/16
to AngularJS
Hi Stephane,

Yes, the injector makes possible what you want. However, I would not do it quite like that. There is no problem in having multiple components using the same selector. Just use the component you need, at the place you need it.
The only reason to do what you propose, is to replace a component, that is used many times throughout the whole app.

PS, I recall a thoughtgram blog post over exactly this issue, it might be worth for you to trace that down.

Regards
Sander

Stephane Dion

unread,
May 31, 2016, 9:47:54 AM5/31/16
to ang...@googlegroups.com
On thoughtgram blog , I only found examples of DI with service. I want the be able to extend an application by only replacing some services, components, templates and css.
Replacing a component doesn't work.  In my example,  AppComponent is still using the FooComponent,  not the FooOverrideComponent.  

I found a solution but it is not very elegant,  I would prefer using dependency injection.

class myViewResolver extends ViewResolver{
resolve(component): ViewMetadata {
var view = super.resolve(component);

if (component.name === 'AppComponent') {
view.directives[0] = FooOverrideComponent; //Replace FooComponent by FooOverrideComponent
}
return view;
}
}

bootstrap(AppComponent, [
provide(FooComponent, {useClass:FooOverrideComponent}),
provide(ViewResolver, {useClass:myViewResolver})
]);

Thanks,
Stephane

--
You received this message because you are subscribed to a topic in the Google Groups "AngularJS" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/angular/wvzbPkwrb_E/unsubscribe.
To unsubscribe from this group and all its topics, send an email to angular+u...@googlegroups.com.
To post to this group, send email to ang...@googlegroups.com.
Visit this group at https://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages