如何将子组件传递给父级兄弟组件?

时间:2017-10-11 08:21:06

标签: angular

我希望在bucket-modal.component.ts上的用户鼠标悬停/鼠标离开时显示来自list.component.ts的弹出窗口。 如何在list.component.tsbucket-modal.component.ts之间进行通信?我的代码在这里。

list.component.ts

@Component({    
    selector: 'list',
    templateUrl: 'list.component.html',
    styleUrls: ['list.component.css'],
})

export class ListComponent implements OnInit {
 @Input() state: boolean;
    @Output() toggle = new EventEmitter();
    onHover() {
    this.state = true;
    this.toggle.emit(this.state);
    console.log("state is ----------" + this.state);
    }
    onHoverOut() {
    this.state = false;
    this.toggle.emit(this.state);
    console.log("state is------ " + this.state);
    }
}

list.component.html

<a (mouseover)="onHover()" (mouseleave)="onHoverOut()">random Link list</a>

listdetails.component.ts

@Component({

    selector: 'app-list-detail',
    templateUrl: 'app-list.component.html',
    styleUrls: ['app-list.component.css'],
})


export class ListDetailComponent implements OnInit {


}

listdetails.component.html

<list [elementslist]="listdetails" listingtype="3"></list>
<list [elementslist]="listdetails" listingtype="3"></list>
<list [elementslist]="listdetails" listingtype="3"></list>
<bucket-modal [(showMeaddBucket)]="show2ClickedBucket" [state]="PopUpshow" (toggle)="PopUpshow=$event"></bucket-modal>

斗modal.component.ts

@Component({    
    selector: 'bucket-modal',
    templateUrl: 'bucket-modal.component.html',
    styleUrls: ['bucket-modal.component.css'],
})



export class BucketModalComponent implements OnInit {

      @Input() state: boolean;
      @Output() toggle = new EventEmitter();
    onHover() {
        this.state = true;
        this.toggle.emit(this.state);
        console.log("state is " + this.state);
    }
    onHoverOut() {
        this.state = false;
        this.toggle.emit(this.state);
        console.log("state is " + this.state);
    }
}

2 个答案:

答案 0 :(得分:1)

我认为最简单的方法是在BucketModalComponent中创建一个公共方法,它将显示弹出对话框。像

这样的东西
export class BucketModalComponent implements OnInit {
  showDialog(): void {
    // Open the popup dialog
  }
}

然后你可以在listdetails.component.html

中调用它
<list ... (toggle)="modal.showDialog()"></list>
<bucket-modal #modal ... ></bucket-modal>

答案 1 :(得分:0)

让我们考虑一下这样的组件,

// Components
-parent 1
    - child 11
-parent 2
    - child 21
-parent 3
    - chils 31

// NgModule
- NgModule
    -> that has all these components
    -> Provider : CommonService

现在我想将子11中的数据传递给所有父(1,2,3)

在这种情况下,您需要服务,并且该服务需要处于模块级别,例如CommonService 现在,您需要做的就是将该服务注入您要访问的组件中 那些数据。

您还可以在CommonService和FireItFrom child11中创建eventEmitter 并在所有父组件中订阅该eventEmitter。

相关问题