简体   繁体   中英

variable from one component to another is not working in angular 9

I am working in Angular 9.1.3 .

I have two component admin and header . I have to print/pass the variable from admin to header component. But saying the variable is undefined .

My admin component: admin.component.ts

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { first } from 'rxjs/operators';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.scss']
})
export class AdminComponent implements OnInit {
  access_token:any;
  userdata: any;
  userName: any;
  parentMessage:any;
  constructor(private authService: AuthService, private router: Router) { }
  ngOnInit() {
    this.getetUser();
    this.parentMessage = "message from Admin";
  }
  }

My header component: header.component.ts

import { Component, OnInit, Input  } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';
import { AdminComponent } from '../admin/admin.component';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  @Input("parentMessage") modifiedName;
  ngOnInit() {
    console.log("This is the admin data "+ this.modifiedName); //This is the admin data undefined
  }
}

You need to pass the variable from parent to child component through HTML.

In the admin.component.html

    <app-header [parentMessage]="parentMessage"></app-header>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM