如何在两个子组件之间使用@Input @Output

问题描述 投票:0回答:1

我有两个组件 - child1 和 child2。如何使用@Input和@Output组件共享来实现以下场景。 下面是在单个组件中并排有两个 div 的示例代码。 但我需要以一种方式实现,其中一个 div 在一个组件中,另一个 div 在另一个组件中,并在这两个组件之间传递数据。

<div class="parentDiv">
        <div class="parentBox1" (click)="movetoparentbox2(childBox1)" *ngFor=" let childBox1 of childArray">
            {{childBox1}}
        </div>
    </div>
    
    <div class="parent2Div">
    
        <div class="parentBox2" (click)="movetoparentbox1(childBox2)"  *ngFor="let childBox2 of child2Array">
            {{childBox2}}
        </div>
    </div>
    
    
    
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './child1.component.html',
      styleUrls: ['./child1.component.css']
    })
    export class Child1Component {
      childArray = [1, 2, 3, 4, 5];
      child2Array = ['a', 'b', 'c', 'd', 'e']
      filtered!: any[];
    
      movetoparentbox2(name: any) {
        this.child2Array.push(name);
        this.filtered = this.childArray.filter((el) => el != name);
        console.log("filtered", this.filtered)
        this.childArray = this.filtered;
      }
    
      movetoparentbox1(name: any) {
        this.childArray.push(name);
        this.filtered = this.child2Array.filter((el) => el != name);
        this.child2Array = this.filtered;
      }
    }

.parentDiv {
    width: 100px;
    height: 500px;
    background-color: brown;
    float: left;
    margin: 30px;
}

.parent2Div{
    width: 100px;
    height: 500px;
    background-color: blue;
    float:left;
    margin: 30px;

}
.parentBox1 {
   width: 20px;
   height: 20px;
   background-color: blueviolet; 
   margin: 15px;
   padding: 15px;
   float: left;
}

.parentBox2{
    width: 20px;
    height: 20px;
    background-color: green; 
    margin: 15px;
    padding: 15px;
    float: left;
}
angular input output
1个回答
0
投票

输入和输出仅在组件具有父子关系时才起作用

您可以使用服务或将逻辑放在父级中(数组属于父级,函数 moveToparenets 也在父级中......)

您将数组作为输入传递给您的孩子

.....child-component...

@Input() childArray:any[]
@Output() move:EventEmitter<string>=new EventEmitter<string>()

click(name:string){
   this.move.emit(name)
}
© www.soinside.com 2019 - 2024. All rights reserved.