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

时间:2018-08-28 14:52:28

标签: angular angular2-template angular6

signin.component.ts(子组件)

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() 
  {

  }

}

topmenucomponet.ts(父组件)

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'
  }
}

我尝试过,但是没有用。我想访问(sigin.component.ts)中的(topmenu.component.ts)消息。您可以提供任何建议如何访问一个组件以及另一组件的值或方法吗?我正在使用各种概念的viewchild和输入,但由于无法读取属性消息值而无法正常显示错误。

2 个答案:

答案 0 :(得分:0)

来自rxjs的内部appservie服务文件导入行为主题

 import { BehaviorSubject } from 'rxjs/BehaviorSubject';

然后定义BehaviorSubject

formValue= new BehaviorSubject({'username':''});

使用next方法跨组件共享数据

父组件

 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];    
  }

答案 1 :(得分: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()方法