3

AuthComponent

    import { TopnavComponent } from './../topnav/topnav.component';
    import { Component, OnInit,ViewContainerRef } from '@angular/core';
    import {AuthService} from "./auth.service";
    import { NgForm } from '@angular/forms';
    import {Router} from "@angular/router";
    import {Profile} from "./auth.model";
    import {Http,Request,Response,Headers, RequestOptions} from "@angular/http";
    import { HttpClient, HttpHeaders } from '@angular/common/http';
    import { Observable } from 'rxjs';

    @Component({
        selector: 'app-auth',
        templateUrl: './auth.component.html',
        styleUrls: ['./auth.component.css'],
        providers:[TopnavComponent]
    })
    export class AuthComponent implements OnInit {
    constructor(private authUser: AuthService, private router: Router,public topnav:TopnavComponent) {};
    callMethod() {

           document.cookie = 'uid='+ this.isAuthSuccess.profile[0].guProfileId;
                    document.cookie = 'isInstructor='+ this.isAuthSuccess.profile[0].isInstructor;
                    document.cookie = 'isStudent='+ this.isAuthSuccess.profile[0].isStudent;
                    this.topnav.changeState();
                    this.router.navigateByUrl('/home');
            });
        }
    }

TopnavComponent

import { Component, OnInit } from '@angular/core';
import {Http,Request,Response,Headers, RequestOptions} from "@angular/http";
import { HttpClient, HttpHeaders } from '@angular/common/http';
import {Router, ActivatedRoute} from "@angular/router";
import { Observable } from 'rxjs';
import {AuthService} from "../auth/auth.service"

@Component({
    selector: 'app-topnav',
    templateUrl: './topnav.component.html',
    styleUrls: ['./topnav.component.css']
})
export class TopnavComponent implements OnInit {
    hideCourse=false;
    constructor(private router: Router,private auth:AuthService) { }
    changeState(){
        this.hideCourse=!this.hideCourse;
    }
}

TopnavComponent.html

<button (click)="callMethod()">Submit</button>
<ul class="navbar-nav mr-auto" *ngIf="hideCourse">
    <li class="nav-item dropdown">
        <a class="nav-link" routerLink="/auth">Sign In</a>
    </li>
</ul>

I have above components in my Angular 2 website,where I'm calling callMethod where I do certains things and then calling topnavComponent's changeState to hide the Sign In button from navigation bar. I'm getting the correct value for hideCourse property which is assigned to *ngIf, but it's not updating the view as wanted.

Can anyone tell me a solution for my scenario.

Thanks.

Suvethan Nantha
  • 2,404
  • 16
  • 28

2 Answers2

0

I won't try to understand your code, but simply give you the code to inject a component instance into another component (remember to import the unkown key words).

constructor(
  @Inject(forwardRef(() => TopnavComponent)) private topnav: TopnavComponent
)

Now you can use

this.topnav.changeState();
  • 1
    @Suvethan, use a service https://stackoverflow.com/questions/48069554/how-to-execute-a-function-from-another-component-that-is-not-a-sibling-of-the-fi – Eliseo Jan 05 '18 at 11:59
  • You're the one that asked for it, don't lecture me on how bad is it ... And it's a bad practice only beczuse it creates a dependency between the two components, but let's face it, you're making an application, you're starting it, and you will certainly not use your component elsewhere. –  Jan 05 '18 at 12:10
  • By the way, you're saying that while you try to inject a component into another. You just didn't have the code, so I provided it to you. –  Jan 05 '18 at 12:12
  • @Eliseo In my case I'm getting the value but its not updating the view. – Suvethan Nantha Jan 05 '18 at 12:33
  • That's a lucky shot because nothing tells angular which instance of your component to use. –  Jan 05 '18 at 12:37
0

There are many options to communicate two components. Using a service we can subscribe to a Observable or simply use a getter. this aproach it's more confortable with the "philosophy" of separate component. Your components don't need know about the other one

Service

@Injectable()
export class UtilCommonService {

  sharedData:any;  //<--a public variable that can be changed
  private dataSource = new Subject<any>();
  data = this.dataSource.asObservable();  //<--an Observable
  change(param:any) {   //<--function to force a change
     this.dataSource.next(param)
  }
  constructor() { }
}

component-uno

@Component({
  selector: 'app-app-uno',
  template:`<button (click)="buttonClick()">Push me</button>`
})
export class AppUnoComponent implements OnInit {

  constructor(private utilCommonService:UtilCommonService) { }

  ngOnInit() {
  }
  buttonClick()
  {
    this.utilCommonService.change("Hola mundo"); //<--call to change of the service
    this.utilCommonService.sharedData="Adios mundo"; //<--simply change the value of the variable
  }
}

Component dos

@Component({
  selector: 'app-app-dos',
  template:`<p>Data:{{data}}</p>
  <p>Shared Data:{{sharedData}}</p>`
})
export class AppDosComponent implements OnInit {

  constructor(private utilCommonService: UtilCommonService) { }
  data:any;
  get sharedData() //<--a getter
  {
    return this.utilCommonService.sharedData;
  }
  ngOnInit() {
    this.utilCommonService.data.subscribe((param: any) => { //<--subscribe to an observable
      this.data=param;
    });
  }
}

AppMain

@Component({
  selector: 'app-app-main',
  template:`<app-app-uno></app-app-uno>
  <app-app-dos></app-app-dos>`
})
export class AppMainComponent{
  constructor() { }
}
Eliseo
  • 50,109
  • 4
  • 29
  • 67