Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function of component from template of another component in ionic 2

Tags:

angular

ionic2

I want to call a function of component from template of another component in

ionic 2.I get a dashboard in in my app dashboard.html using home.ts

component.

<ion-content> 
<div class="dashboardSection">

            <a href="" (click)="fetchAllClass()">
                <div class="header padding text-center classes common">
                    <img src="assets/images/icos_15.png" alt="Your logo here"  width="50%" height="auto"/>
                    <p class="Sectiontitle">STUDENTS</p>
                </div>
            </a></div>
</ion-content>

this is showing with the help of home.ts

doLogin(event) {    
    var user1 =this.loginForm.value;
    var password = this.loginForm.controls.password.value;
    this.homeService.doLogin(user1).subscribe(
        user =>{
            this.user = user.results; 
            this.storage.set('isLoggedIn', 'shahjad');
            this.navCtrl.setRoot(DashboardComponent, {thing1: user });
        },
        err => {
            console.log(err);
        },
        () => console.log('login complete')

        );
}

Now, I want to call student component'function from dashboard Component

I created student component like students.ts

@Component({

    selector: 'page-students',
    templateUrl: "./students.html"
})
export class StudentsComponent {
    dashboardItem: any;
    mode = "Observable";
    errorMessage: string;

    constructor(public fb: FormBuilder,private studentsService: StudentsService,public navCtrl: NavController,private storage: Storage,private menu: MenuController) {}

    fetchAllClass(event) {  

        alert("fd");
    }
}
like image 978
Shahzad Intersoft Avatar asked Mar 08 '23 18:03

Shahzad Intersoft


2 Answers

If your studentcomponent is a direct child of dashboard you can use a viewchild.

<page-student #student></page-student>

In you component:

@ViewChild('student') student: StudentComponent
like image 84
Robin Dijkhof Avatar answered Apr 27 '23 09:04

Robin Dijkhof


You definitely should take a look at Angular's services and how to build a custom one. You can see a thread about this here.

Basically, you will create an Injectable, add it to your NgModule (or a shred module) and then inject then in the components you need to use it. Other great tutorial is here.

like image 33
Christian Benseler Avatar answered Apr 27 '23 09:04

Christian Benseler