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

Angular Universal causes SASS imports to malfunction

Check out this sample app that you can download to see the issue in action: https://github.com/chrillewoodz/ng-boilerplate/tree/universal I am currently working on implementing angular universal, but I'm encountering an error with a SCSS import in o ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

Guide to refreshing filters once data is updated in PrimeNG tables?

Whenever I add new rows to the table, the display updates dynamically. However, any filters I have applied only reflect the initial data. https://i.stack.imgur.com/5Nuxe.png For example, if I use the "startsWith" filter on a column labeled "Title" with a ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

The chosen Angular material pre-built theme of indigo-pink does not seem to be applied properly

Within my styles.scss @import '~@angular/material/prebuilt-themes/indigo-pink.css'; I have also attempted this in my index.html <link href="node_modules/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet" /> Finally, I m ...

Tips for updating an array in TypeScript with React:

Encountering an issue while updating my state on form submission in TypeScript. I am a newcomer to TS and struggling to resolve the error. enum ServiceTypeEnum { Replace = 'replace product', Fix = 'fix product', } interface IProduc ...

Personalize the Legend of a Pie Chart with chart.js

My current setup involves using the ChartModule in PrimeNG, which is powered by Chart.js. The issue I'm facing is with a pie chart that displays different types of data, one of which is deliveries. Sometimes there are multiple instances of deliveries ...

What is the best way to determine the data type of one property in an array of objects based on another property

I have been working on creating a straightforward parser that relies on rules provided by the constructor. Everything seems to be running smoothly, but there are some issues with data types. interface RuleBase { parse(text: string, params: Record<stri ...

When merging multiple prop definitions using Object.assign in defineProps, Vue props can be made optional

I have defined a const called MODAL_OPTION_PROP to set common props for a modal: export const MODAL_OPTION_PROP = { modalOption: { type: Object as PropType<ModalOptionParams>, default: DEFAULT_MODAL_OPTION, }, }; I am trying to use it in ...

Using private members to create getter and setter in TypeScript

Recently, I developed a unique auto getter and setter in JavaScript which you can view here. However, I am currently unsure of how to implement this functionality in TypeScript. I am interested in creating an Object Oriented version of this feature if it ...

Encountering Issues with TypeScript Strict in Visual Studio Code Problems Panel

I have discovered that I can optimize my TypeScript compilation process by utilizing the --strict flag, which enhances type checking and more. Typically, I compile my TypeScript code directly from Visual Studio Code with a specific task that displays the c ...

What is the best way to create a universal function that can return a promise while also passing along event

I created a specialized function that waits for an "EventEmitter" (although it's not completely accurate as I want to use it on other classes that have once but don't inherit from EventEmitter): export function waitEvent(emitter: { once: Function ...

Simple steps to transform the "inputs" syntax into the "@Input" property decorator

There's this code snippet that I need to modify: @Component({ selector: 'control-messages', inputs: ['controlName: control'], template: `<div *ngIf="errorMessage !== null">{{errorMessage}}</div>` }) Is the ...

What is the best method to create a TypeScript dictionary from an object using a keyboard?

One approach I frequently use involves treating objects as dictionaries. For example: type Foo = { a: string } type MyDictionary = { [key: string]: Foo } function foo(dict: MyDictionary) { // Requirement 1: The values should be of type Foo[] const va ...

Navigating to different HTML pages by utilizing <a> elements in Angular 2

As a newcomer to Angular 2, I've decided to build my personal website using this framework. The main page of my website contains bio information, while the other page will feature blog content. Both pages will have a shared header and footer, but diff ...

An issue has occurred where all parameters for the DataService in the D:/appangular/src/app/services/data.service.ts file cannot be resolved: (?, [object Object])

Upon running the command ng build --prod, an error is encountered. Error in data.service.ts: import { BadInput } from './../common/bad-input'; import { AppError } from './../common/app-error'; import { Injectable } from '@angular ...

Displaying the focus icon on the active tab using Angular Material

I am currently utilizing Angular material to dynamically generate tabs in my HTML code. I'm trying to display a drop arrow icon on the active or selected tabs, but I am facing some challenges with the implementation. Below is the code snippet I have ...

Efficient Loading and Smooth Scrolling with Angular2 (version 7)

I'm struggling to display a component upon the initial page load using lazy loading, where the content is only loaded when it's in view. For instance: - With 10 components on the page, I aim to show/scroll to component number 7 when the page lo ...

The issue arises when trying to pass multiple parameters with the Angular 2 router and encountering

After creating a sample Plunker to pass multiple parameters to the next page, I encountered an issue where the crisis center routing failed to work properly upon clicking on items. See the demonstration on Plunker here: http://plnkr.co/edit/ngNSsKBzAuhaP0E ...

Is it possible to denote two "any" as the same thing in a TypeScript function signature?

Here is a function to extract items from an array based on a checker function: function extractItemsFromArray(array: any[], isItemToBeRemoved: (item: any) => boolean) { let removedItems = []; let i = array.length; while(i--) if(isItemToBeRemo ...