Angular 9 组件交互

Posted

技术标签:

【中文标题】Angular 9 组件交互【英文标题】:Angular 9 component Interaction 【发布时间】:2020-09-15 07:08:30 【问题描述】:

我的 Angular 项目中有两个组件,我需要一个组件中的数据才能从另一个组件获取。seat-modal 是我的数据所在的位置。following 是 seat-modal.ts。

    import  Component, OnInit  from '@angular/core';
import NgbModal, ModalDismissReasons from '@ng-bootstrap/ng-bootstrap';
import FormBuilder, FormGroup, Validators from '@angular/forms';
import  SocketService from '../../_services/socket.service';


@Component(
  selector: 'app-seat-modal',
  templateUrl: './seat-modal.component.html',
  styleUrls: ['./seat-modal.component.less']
)
export class SeatModalComponent implements OnInit 

  formRequestSeat: FormGroup;
  socket;
  public seat;
  showModal: boolean;
  public screenName: string;

  constructor(private socketService: SocketService,
              private modalService: NgbModal,
              private formBuilder: FormBuilder)  

  ngOnInit()
    this.formRequestSeat = this.formBuilder.group(
      seatRequest: ['', Validators.required]
    );
  

  hide()
    this.modalService.dismissAll();
  

  join(seat)
    const userToken = localStorage.getItem('userToken');
    const tableToken = localStorage.getItem('tableToken');
    this.socket = this.socketService.init(userToken);
    const displayName = this.formRequestSeat.controls.seatRequest.value;
    if (!displayName)
      alert('Please enter a display name');
      return;
    
    this.socket.emit('join', tableToken, displayName, seat, (data) => 
      // data.forEach((index, value) => 
      //   // this.seatsFormGroup.controls['seat-' + index].value(value);
      // );
      console.log(data.screenName);
      this.screenName = data.screenName;


    );
    this.hide();

  



关注的是seat-modal.html

    <div class="modal" id="seat.id" [style.display]="showModal ? 'block' : 'none'">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Seatseat.id</h4>
        <button type="button" class="close" data-dismiss="modal" (click)="hide()">&times;</button>
      </div>
      <!-- Modal body -->
      <div class="modal-body">
        <form [formGroup]="formRequestSeat" (submit)="join(seat.id)">
          <div class="form-group col-6">
            <label for="name">Your Name</label>
            <input formControlName="seatRequest" type="text"/>
          </div>
        <div>
          <button type="submit" class="button-request-seat">Request The Seat</button>
        </div>
        </form>
      </div>

    </div>
  </div>
</div>
<app-play-game [parentData]="screenName"></app-play-game>

Follow 是我的另一个组件 ts

 import Component, Input, OnInit from '@angular/core';
    import AlertService from '../../_services/alert.service';
    import SocketService from '../../_services/socket.service';
    import  FormBuilder, FormGroup, FormArray, FormControl, 
    ValidatorFn 
    from '@angular/forms';
    import  of  from 'rxjs';
    import NgbModal from '@ng-bootstrap/ng-bootstrap';
    import SeatModalComponent from '../../_components/seat-modal/seat- 
    modal.component';
    @Component(
    selector: 'app-play-game',
    templateUrl: './play-game.component.html',
    styleUrls: ['./play-game.component.less']
    )
    export class PlayGameComponent implements OnInit 
    @Input() public parentData;
    seatsFormGroup: FormGroup;
    seats = [];
    showModal: boolean;
    public seatModalRef;
    private socket;
    constructor(private socketService: SocketService,
              private formBuilder: FormBuilder,
              private modalService: NgbModal) 

    this.seatsFormGroup = this.formBuilder.group(
      'seat-0': [''],
      'seat-1': [''],
      'seat-2': [''],
      'seat-3': [''],
      'seat-4': [''],
      'seat-5': [''],
      'seat-6': [''],
      'seat-7': [''],
      'seat-8': [''],
      'seat-9': ['']
    );

    for (let i = 0; i < 10; i++) 
      this.seats.push( 'seat-' + i);
    
    

    ngOnInit()
    console.log('name=' + this.parentData);
    


    sit(seat)
    this.seatModalRef = this.modalService.open(SeatModalComponent);
    this.seatModalRef.componentInstance.seat = seat;
    this.seatModalRef.componentInstance.showModal = true;
    
    

我尝试了一个 console.log(this.parentData) 但它是未定义的。请帮助我的代码我是角度的初学者。

【问题讨论】:

你在哪里控制台记录这些数据? 在我的游戏组件中的 ngOnInit 内 【参考方案1】:

您的座位组件应该从

export class SeatModalComponent implements OnInit public screenName: 'Sahan';

export class SeatModalComponent implements OnInit public screenName: string = 'Sahan';

目前您已将 Sahan 字符串作为类型而不是值赋予它。冒号 (:) 用于给出类型,equals(=) 用于赋值。

【讨论】:

我都试过了 public screenName: string = 'Sahan';和 public screenName ='Sahan';我越来越不确定 您在哪里进行控制台日志记录? 你从哪里导入@input? 从 '@angular/core' 导入 Component, Input, OnInit; 你能在你的问题中发布你完整的游戏模式吗?【参考方案2】:

请用下面的方法修复 SeatModalComponent。

public screenName: String = 'Sahan';

【讨论】:

以上是关于Angular 9 组件交互的主要内容,如果未能解决你的问题,请参考以下文章

Angular Observable 组件和服务交互

Angular2:通过引用传递组件之间的交互

Angular - 从特定组件实例获取数据,以便能够通过单击按钮与之交互

使用服务不起作用的 2 个组件之间的交互 ​​Angular 6/7

Angular 9 - 渲染有限数量的组件的孩子

Angular 9:销毁子组件后向父组件发送数据