@viewChild不触发模式弹出并抛出错误triggerModal不是函数-Angular

时间:2019-12-04 06:29:42

标签: angular typescript

我不知道为什么未从父组件触发click事件以显示bootstrap 3模态。像下面这样的抛出错误

ERROR TypeError: this.target.triggerModal is not a function

到目前为止,我已经拥有了

componentPrnt

@ViewChild('target') private target: modalComponent;

ngOnInit(){
this.target.triggerModal();
}

<btton #target>open modal</button>

modalComponet

export class ModalComponent implements OnInit {     
    constructor() { }
    ngOnInit() {        

  }    
    triggerModal() {
        console.log('model opened');
        $('#myModal').modal("show");
    }
}


<div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
                <p>Some text in the modal.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

3 个答案:

答案 0 :(得分:1)

由于targetModalComponent的类型,因此它将是:

.html

<button (click)="openModal()">open modal</button>
<app-modal #target></app-modal>

.ts

@ViewChild('target') private target: ModalComponent;

openModal(){
  this.target.triggerModal();
}

答案 1 :(得分:1)

您可以使用@ViewChild进行以下操作:

  @ViewChild(ModalComponent) modalC:ModalComponent; 
  parentButtonHandler(){
     this.modalC.triggerModal();
  }

从父母那里打开孩子的模态的工作演示是: demo

答案 2 :(得分:0)

我已解决问题,解决方案在StackBlitz中。将来可能有人需要