Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a component method from HTML in Angular2

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>
like image 265
Gerard Avatar asked Feb 06 '17 11:02

Gerard


People also ask

How do you call a component in HTML?

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.

How do you call a component method in service?

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.

How do you call a function in another component angular using RXJS?

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.."); } //... }


1 Answers

{{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>
like image 154
Günter Zöchbauer Avatar answered Oct 01 '22 00:10

Günter Zöchbauer