Reusable components with NgContent and TemplateRef – Jaspero

  • Reusable components with NgContent and TemplateRefAngular components are all about reusability, and Angular provides us with a bunch of tools to achieve this.
  • As with everything else in coding, it’s great to start with an example.@Component({ selector: ‘example-one’, template: ` pContent gets inserted here:/p ng-content/ng-content `,})export class Example {}@Component({ selector: ‘my-app’, template: ` example-one/example-one `,})export class App {}Basically any content you add between the example/example tags replaces the ng-content/ng-content element.
  • If you are familiar with ng-transclude from Angular 1, this acts in much the same way, only it’s even simpler to use this time around.
  • You can even bind any method or property from the parent component without any problem or additional boilerplate code.
  • For example adding a method in the AppComponent and calling it from in example/example will work:@Component({ selector: ‘example-one’, template: ` pContent gets inserted here:/p ng-content/ng-content `,})export class Example {}@Component({ selector: ‘my-app’, template: ` example-one button /example-one `,})export class App { name = ‘Jasper Jaspery’ logSomething() { console.log(‘I got called: ‘, this.name); }}Read full article…

Angular components are all about reusability, and Angular provides us with a bunch of tools to achieve this. In this article we’ll be looking into two of those: ng-content and TemplateRef. Ng-content…

@_techradar: adeeb (@_adeeb) | Reusable components with NgContent and TemplateRef   #html #angularjs…

Angular components are all about reusability, and Angular provides us with a bunch of tools to achieve this. In this article we’ll be looking into two of those: ng-content and TemplateRef.

Ng-content is really simple to understand and use. As with everything else in coding, it’s great to start with an example.

Basically any content you add between the tags replaces the element. If you are familiar with ng-transclude from Angular 1, this acts in much the same way, only it’s even simpler to use this time around. You can even bind any method or property from the parent component without any problem or additional boilerplate code. For example adding a method in the AppComponent and calling it from in will work:

Reusable components with NgContent and TemplateRef – Jaspero

You might also like More from author

Comments are closed, but trackbacks and pingbacks are open.