Parent component interacting with child component

In my application, I have a header component along with registration and login components. The selector of the header component is used in both the login and registration components. There is also a button in the header that displays as a login button if the user is on the /registration URL. When clicked, this button changes the route to the login page.

this.router.navigate(['/Login']);

My goal is to change this button to display 'Registration' when the user moves to the login page. How can I control the button from both the login and registration components?

Answer №1

I managed to achieve this using the @Input API.

App.ts

import {Component,bind} from 'angular2/core';
import {ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router';
import {bootstrap}  from 'angular2/platform/browser';

import{ComponentOne} from 'src/cone';
import{ComponentTwo} from 'src/ctwo';

@Component({
  selector: 'my-app',
  template: `
    <h1>Component Router</h1>
    <nav>
    <hr>
      <a [routerLink]="['ComponentOne']">Login</a><hr/>
      <a [routerLink]="['ComponentTwo']">Registration</a>
    </nav>
    <hr>
    <router-outlet></router-outlet>
  `,
  directives: [ROUTER_DIRECTIVES]
})
@RouteConfig([
  {path:'/component-one', name: 'ComponentOne', component: ComponentOne useAsDefault:true},
  {path:'/component-two', name: 'ComponentTwo', component: ComponentTwo}
])
export class AppComponent { }

    bootstrap(AppComponent, [
      ROUTER_PROVIDERS,bind(APP_BASE_HREF).toValue(location.pathname)
    ]);

Login.ts OR cone.ts

 import {Component,View,ViewChild} from 'angular2/core';
 import {HeaderCmp} from 'src/header';


 @Component({
    template: `

    <header text="Registration"></header>
    <hr>
    <h1>Login</h1>
    `,
    directives:[HeaderCmp] 
  })

  export class ComponentOne {

      constructor(){ 
             console.log("first component being called");
      }

  }

Registration.ts OR ctwo.ts

import {Component,View} from 'angular2/core';
 import {HeaderCmp} from 'src/header';

 @Component({
    template: `
    <header text="Login"></header>
    <h1>Registration </h1>
    `,
    directives:[HeaderCmp]
  })

  export class ComponentTwo{
    constructor(){

      console.log("Second component being called");
    }
  }

Header.ts

import {Component,View,Input} from 'angular2/core';
 import {sharedService} from 'src/sharedService';

 @Component({
   selector:'header',
    template: `
    <h4>Header </h4>
    <button>{{text}}</button>
    `
  })

  export class HeaderCmp{
     @Input() text: string='myText';

      constructor(){
               console.log("Header being called");
      }

 }

View Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Anticipate receiving a 'Type' returned by external library functions

I've recently started learning TypeScript and have encountered a situation where I need to assign a type to a variable that is returned from a third-party library function with its own type definition. For instance: import {omit} from 'lodash&ap ...

Tips for resolving TS7022 issue within Vue Composition API

I encountered an issue while attempting to import a component in my file that generated the following error message: TS7022: 'default' implicitly has type 'any' because it does not have a type annotation and is referenced directly or in ...

Tackling the white-source security problem in npm libraries

A security advisory from White-source has identified high vulnerability issues with certain libraries used in your repository, specifically with yargs-parser: 1. build-angular-0.13.8.tgz (Root Library) node-sass-4.11.0.tgz sass-graph-2.2 ...

How can you implement Higher Order Components as a decorator in TypeScript?

Currently, I am attempting to develop a decorator that accepts an argument from React's Context provider. When creating a higher-order component (HOC), the process is straightforward: interface DashboardProps { user: User; } class Dashboard exten ...

Utilizing the await keyword within a forkJoin operation in TypeScript

I am facing an issue where I need to fetch a new result based on the old result. When a specific parameter in my primary call is X, it should trigger another function. However, the problem I'm encountering is that the scope of the program continues ru ...

Ways to adjust the size of a Primeng autocomplete with multiple selections?

I'm new to Angular and I'm attempting to adjust the width of a primeng auto complete component in order to fill the column of a table. I've already experimented with using style="width: 100%" but that approach hasn't yielded any result ...

If you're trying to work with this file type, you might require a suitable loader. Make sure you

Attempting to utilize Typescript typings for the Youtube Data API found at: https://github.com/Bolisov/typings-gapi/tree/master/gapi.client.youtube-v3 Within the Ionic framework, an error is encountered after running 'Ionic Serve' with the follo ...

Error is being thrown due to defining a variable after it has already been declared and

Before I use a variable, I encountered the issue of using it before its definition, interface IProps extends WithStyles<typeof STYLES>; const STYLES = () => ({ }) Although it didn't cause any errors, a warning appeared: STYLES used befo ...

Issue with Typescript typing for the onChange event

I defined my state as shown below: const [updatedStep, updateStepObj] = useState( panel === 'add' ? new Step() : { ...selectedStep } ); Additionally, I have elements like: <TextField ...

Animated scrolling in Angular

I am working on a webpage using Angular, where each module is a component with an animation. However, I am facing an issue where the animation only runs when the page loads, but I want it to happen while the component is visible on the screen. One approa ...

Exploring ways to send data to WebView in Flutter

How can I pass the location obtained in my Flutter app to a WebView for further processing within the opened site? var userLocation = Provider.of<UserLocation>(context); Here is my WebView setup: WebView( initialUrl: widget.url, javasc ...

Sharing Information Across Angular Routes

I've been encountering a slight issue when working with routes in Angular 4. Whenever I attempt to pass data from one component to another using navigate('root', data), all I end up receiving is [object Object],[object Object],[object Object ...

Display items according to the visible element

Just starting with Angular and could use some guidance In my header component, I have a bootstrap navbar consisting of ul and li elements along with a router outlet. <app-header></app-header> <router-outlet></router-outlet> I&apo ...

What is the correct way to utilize window.scrollY effectively in my code?

Is it possible to have a fixed header that only appears when the user scrolls up, instead of being fixed at the top by default? I've tried using the "fixed" property but it ends up blocking the white stick at the top. Adjusting the z-index doesn&apos ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

Using RxJS switchMap in combination with toArray allows for seamless transformation

I'm encountering an issue with rxjs. I have a function that is supposed to: Take a list of group IDs, such as: of(['1', '2']) Fetch the list of chats for each ID Return a merged list of chats However, when it reaches the toArray ...

Comparing the properties of objects in two arrays can be done most effectively by utilizing the most efficient method available

In Angular2, I am looking for a more efficient way to check if an object's property in one array matches a property in another array and return the value. Is there a method similar to using .contains in Swift? doSomething(){ for (let element1 of ...

Having to reinstall node modules is a repetitive task that must be done after each build of an Angular

Formulating this question has been quite challenging for me. I really hope it is clear. Despite my extensive searches, both on this platform and beyond, I have not been able to find any reference to the behavior I am experiencing. For the past few ...

Issue with integrating Bootstrap into Angular 2

When attempting to link to the bootstrap.css file located in the node_modules folder within index.html, I encountered an error. The application's folder structure is as follows: ecommerce-app/node_modules ecommerce-app/src/app/index.html All attem ...

Issue with NGXS Selector Observable not reflecting updated state

My issue is that when I update the state, my selector does not pull the new values. I have defined the selector in my state and I can see the state values getting updated. However, the selector in my component is not fetching the latest values. Even though ...