I'm working on a project and I realize a lot of my components share an HTML snippet to something like:
<div class>
<button type="button" (click)="example()">Label</button>
...
</div>
Each component has a different click binding, and I'd like to abstract the shared HTML part to a component keeping that in mind. I'm assuming working with routing is the way to go here?
CodePudding user response:
Common HTML script can be moved into it's own component, which can then be re-used in other components that use the same HTML.
The HTML script could be wrapped into it's own component, MyComponent which encapsulates the HTML as it's template:
<div class>
<button type="button" (click)="example($event.value)">Label</button>
...
</div>
You can also fire events from the shared component to the parent component using an output accessor and an emitter.
The shared component, MyComponent would have the output emitter and event handler declared as follows:
@Component({
selector: 'app-my-component',
...
})
export class MyComponent implements OnInit {
@Output() clickEvent: EventEmitter<boolean> = new EventEmitter();
...
example(event)
{
this.clickEvent.emit(value);
}
Your shared component can then be used within another component's HTML template using an HTML tag of the selector of the new component:
<app-my-component (clickEvent)="eventClicked($event)"></app-my-component>
An event declared within the parent component would then handle into own events from event notifications from the child component:
eventClicked(value: any) {
// do something with the value from the child component.
}
The above is a basic overview of encapsulating HTML into a shared component and serve as component building blocks within an Angular application.