Is it possible to call a component method from HTML, or should I create another component to handle formatting?
<div *ngFor="let item of items">
<div class="title">{{ item.Title }}</div>
<p>
callComponentMethodHere({{item}})
</p>
</div>
You can call child component in the parent component using the selector as directive on HTML element. Ways to call component by class and directive works same as selector as tag. It just depends on the use case required. To use selector as directive, change is required in the selector of the child component.
This simply can be achieved by injecting service to the component. Then define a method inside the service which takes a function as parameter. The method should save this function as a property of service and call it wherever it wants.
To call another components function in Angular, we can inject the component we want to call the function on as a dependency. export class OneComponent implements OnInit, AfterViewInit { //... ngOnInit() {} public testCall() { alert("I am here.."); } //... }
{{callComponentMethodHere(item)}}
but you should avoid that because the method will be called every time change detection runs. It's better to call the method in code (for example in the constructor()
, ngOnInit()
, or an event handler, assign the result to a property and from the view bind to that property instead.
Calling event handlers is fine of course:
<button (click)="callComponentMethodHere(item)">click me</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With