Angular 如何让一个组件方法调用另一个组件?

Angular 如何让一个组件方法调用另一个组件?,angular,angular2-template,angular6,Angular,Angular2 Template,Angular6,签名组件.ts(子组件) topmenucomponet.ts(父组件) 我试过了,但没用。我想访问(sigin.component.ts)中的(topmenu.component.ts)消息。你能提供一些关于如何访问一个组件和另一个组件值或方法的建议吗?我正在使用各种概念viewchild和input,但它不起作用,因为无法读取属性消息值而显示错误 从rxjs导入AppServi服务文件的内部主题 import { BehaviorSubject } from 'rxjs/BehaviorS

签名组件.ts
(子组件)

topmenucomponet.ts
(父组件)


我试过了,但没用。我想访问(sigin.component.ts)中的(topmenu.component.ts)消息。你能提供一些关于如何访问一个组件和另一个组件值或方法的建议吗?我正在使用各种概念viewchild和input,但它不起作用,因为无法读取属性消息值而显示错误

从rxjs导入AppServi服务文件的内部主题

 import { BehaviorSubject } from 'rxjs/BehaviorSubject';
然后定义行为主体

formValue= new BehaviorSubject({'username':''});
使用下一种方法跨组件共享数据

import { Component, OnInit,Input } from '@angular/core';
import { AfterViewInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material';
import { Data, AppService } from '../../app.service';
import { emailValidator, matchingPasswords } from '../../theme/utils/app-validators';
import { TopMenuComponent } from '../../theme/components/top-menu/top-menu.component';

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss']
})
export class SignInComponent implements OnInit,AfterViewInit {
  loginForm: FormGroup;
  registerForm: FormGroup;
  @ViewChild(TopMenuComponent) top !: TopMenuComponent;
  @Input() hero: TopMenuComponent;

  constructor(public formBuilder: FormBuilder, public router:Router, public snackBar: MatSnackBar,private appservie:AppService)
   {
     localStorage.clear()
    }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      'email': ['', Validators.compose([Validators.required, emailValidator])],
      'password': ['', Validators.compose([Validators.required, Validators.minLength(6)])] 
    });

    this.registerForm = this.formBuilder.group({
      'name': ['', Validators.compose([Validators.required, Validators.minLength(3)])],
      'email': ['', Validators.compose([Validators.required, emailValidator])],
      'password': ['', Validators.required],
      'confirmPassword': ['', Validators.required]
    },{validator: matchingPasswords('password', 'confirmPassword')});

  }

  public onLoginFormSubmit(values:Object):void {
    console.log(values)
    this.appservie.loginuser(JSON.stringify(values)).subscribe(response =>{
      var data = response
      console.log(data)
      console.log(data['user']['username'])
      localStorage.setItem('username',data['user']['username'])
      console.log(this.hero.Message)
    })
    if (this.loginForm.valid) {
      this.router.navigate(['']);

    }
  }

  public onRegisterFormSubmit(values:Object):void {
    if (this.registerForm.valid) {
      this.snackBar.open('You registered successfully!', '×', { panelClass: 'success', verticalPosition: 'top', duration: 3000 });
    }
  }
  ngAfterViewInit() 
  {

  }

}
import { Component, OnInit, Input } from '@angular/core';
import { Data, AppService } from '../../../app.service';

@Component({
  selector: 'app-top-menu',
  templateUrl: './top-menu.component.html'
})
export class TopMenuComponent implements OnInit {
  public currencies = ['USD', 'EUR'];
  public currency:any;
  public flags = [
    { name:'English', image: 'assets/images/flags/gb.svg' },
    { name:'German', image: 'assets/images/flags/de.svg' },
    { name:'French', image: 'assets/images/flags/fr.svg' },
    { name:'Russian', image: 'assets/images/flags/ru.svg' },
    { name:'Turkish', image: 'assets/images/flags/tr.svg' }
  ]
  public flag:any;

  data:any;
  public Message="hai"
  constructor(public appService:AppService) 
  {
   this.data = localStorage.getItem('username')

  }

  ngOnInit() {
    this.currency = this.currencies[0];
    this.flag = this.flags[0];    
  }

  public changeCurrency(currency){
    this.currency = currency;
  }

  public changeLang(flag){
    this.flag = flag;
  }

   value()
  {
    return 'hai'
  }
}
父组件

 public onLoginFormSubmit(values:Object):void {
    console.log(values)
    this.appservie.loginuser(JSON.stringify(values)).subscribe(response =>{
      var data = response
      console.log(data)
      console.log(data['user']['username'])
  if(data['user']['username']){
   this.formValue.next({'username':data['user']['username']});
  }
    })
constructor(private appService:AppService) 
  {
  }

  ngOnInit() {
    this.appService.formValue.subscribe((data)=>{
      this.data = data;
  })
    this.currency = this.currencies[0];
    this.flag = this.flags[0];    
  }
订阅子组件中的数据

import { Component, OnInit,Input } from '@angular/core';
import { AfterViewInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material';
import { Data, AppService } from '../../app.service';
import { emailValidator, matchingPasswords } from '../../theme/utils/app-validators';
import { TopMenuComponent } from '../../theme/components/top-menu/top-menu.component';

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss']
})
export class SignInComponent implements OnInit,AfterViewInit {
  loginForm: FormGroup;
  registerForm: FormGroup;
  @ViewChild(TopMenuComponent) top !: TopMenuComponent;
  @Input() hero: TopMenuComponent;

  constructor(public formBuilder: FormBuilder, public router:Router, public snackBar: MatSnackBar,private appservie:AppService)
   {
     localStorage.clear()
    }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      'email': ['', Validators.compose([Validators.required, emailValidator])],
      'password': ['', Validators.compose([Validators.required, Validators.minLength(6)])] 
    });

    this.registerForm = this.formBuilder.group({
      'name': ['', Validators.compose([Validators.required, Validators.minLength(3)])],
      'email': ['', Validators.compose([Validators.required, emailValidator])],
      'password': ['', Validators.required],
      'confirmPassword': ['', Validators.required]
    },{validator: matchingPasswords('password', 'confirmPassword')});

  }

  public onLoginFormSubmit(values:Object):void {
    console.log(values)
    this.appservie.loginuser(JSON.stringify(values)).subscribe(response =>{
      var data = response
      console.log(data)
      console.log(data['user']['username'])
      localStorage.setItem('username',data['user']['username'])
      console.log(this.hero.Message)
    })
    if (this.loginForm.valid) {
      this.router.navigate(['']);

    }
  }

  public onRegisterFormSubmit(values:Object):void {
    if (this.registerForm.valid) {
      this.snackBar.open('You registered successfully!', '×', { panelClass: 'success', verticalPosition: 'top', duration: 3000 });
    }
  }
  ngAfterViewInit() 
  {

  }

}
import { Component, OnInit, Input } from '@angular/core';
import { Data, AppService } from '../../../app.service';

@Component({
  selector: 'app-top-menu',
  templateUrl: './top-menu.component.html'
})
export class TopMenuComponent implements OnInit {
  public currencies = ['USD', 'EUR'];
  public currency:any;
  public flags = [
    { name:'English', image: 'assets/images/flags/gb.svg' },
    { name:'German', image: 'assets/images/flags/de.svg' },
    { name:'French', image: 'assets/images/flags/fr.svg' },
    { name:'Russian', image: 'assets/images/flags/ru.svg' },
    { name:'Turkish', image: 'assets/images/flags/tr.svg' }
  ]
  public flag:any;

  data:any;
  public Message="hai"
  constructor(public appService:AppService) 
  {
   this.data = localStorage.getItem('username')

  }

  ngOnInit() {
    this.currency = this.currencies[0];
    this.flag = this.flags[0];    
  }

  public changeCurrency(currency){
    this.currency = currency;
  }

  public changeLang(flag){
    this.flag = flag;
  }

   value()
  {
    return 'hai'
  }
}
子组件

 public onLoginFormSubmit(values:Object):void {
    console.log(values)
    this.appservie.loginuser(JSON.stringify(values)).subscribe(response =>{
      var data = response
      console.log(data)
      console.log(data['user']['username'])
  if(data['user']['username']){
   this.formValue.next({'username':data['user']['username']});
  }
    })
constructor(private appService:AppService) 
  {
  }

  ngOnInit() {
    this.appService.formValue.subscribe((data)=>{
      this.data = data;
  })
    this.currency = this.currencies[0];
    this.flag = this.flags[0];    
  }

您可以使用组件实例直接访问属性,而无需执行ViewChild

下面是一个例子

import { Component, OnInit,Input } from '@angular/core';
import { AfterViewInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar } from '@angular/material';
import { Data, AppService } from '../../app.service';
import { emailValidator, matchingPasswords } from '../../theme/utils/app-validators';
import { TopMenuComponent } from '../../theme/components/top-menu/top-menu.component';

@Component({
  selector: 'app-sign-in',
  templateUrl: './sign-in.component.html',
  styleUrls: ['./sign-in.component.scss'],
  providers: [TopMenuComponent]
})
export class SignInComponent implements OnInit,AfterViewInit {
  loginForm: FormGroup;
  registerForm: FormGroup;

  constructor(public formBuilder: FormBuilder, public router:Router, public snackBar: MatSnackBar,private appservie:AppService, private topMenu: TopMenuComponent)
   {
     localStorage.clear()
    }

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      'email': ['', Validators.compose([Validators.required, emailValidator])],
      'password': ['', Validators.compose([Validators.required, Validators.minLength(6)])] 
    });

    this.registerForm = this.formBuilder.group({
      'name': ['', Validators.compose([Validators.required, Validators.minLength(3)])],
      'email': ['', Validators.compose([Validators.required, emailValidator])],
      'password': ['', Validators.required],
      'confirmPassword': ['', Validators.required]
    },{validator: matchingPasswords('password', 'confirmPassword')});

  }

  public onLoginFormSubmit(values:Object):void {
    console.log(values)
    this.appservie.loginuser(JSON.stringify(values)).subscribe(response =>{
      var data = response
      console.log(data)
      console.log(data['user']['username'])
      localStorage.setItem('username',data['user']['username'])
      console.log(this.topMenu.Message);
    })
    if (this.loginForm.valid) {
      this.router.navigate(['']);

    }
  }

  public onRegisterFormSubmit(values:Object):void {
    if (this.registerForm.valid) {
      this.snackBar.open('You registered successfully!', '×', { panelClass: 'success', verticalPosition: 'top', duration: 3000 });
    }
  }

}

我已经更新了构造函数和onLoginFormSubmit()方法

使用行为主题或输出属性绑定可以给出任何示例代码。请提供一个模板,在其中使用这些组件为什么不使用输出?一个组件页面文件夹和另一个组件主题文件夹,但显示错误静态错误。(父组件.ts页面文件夹和子组件.ts主题文件夹)两个组件不同的文件夹。在提供程序中添加
TopMenuComponent
。我会更新我的答案,如果这个答案对您有帮助,请检查此演示,然后请投票并接受。我怀疑父html不显示。如何显示父html一次自动调用父方法html也工作如何实现它。有任何建议吗但显示错误静态注入器错误。(父组件.ts页面文件夹和子组件.ts主题文件夹)两个组件不同的文件夹无关紧要