代码之家  ›  专栏  ›  技术社区  ›  yavg

我只能从父组件视图的HTML调用子组件中包含的模态in,而不能在父组件中调用,为什么?

  •  2
  • yavg  · 技术社区  · 7 年前

    我有一个组件,它又嵌入了一个子组件。基本上,我从父组件调用子组件中包含的模态。只要点击一下父亲的HTML,这个功能就可以完美地工作

    <a type="button"  (click)="modal.show()" >
    

    <a type="button"  (click)="modal.show()">
      open modal
    </a>
    <son #modal ></son>
    

    HTML儿子

    <div mdbModal #mymodal="mdbModal" class="modal fade" id="mymodal" tabindex="-1" role="dialog"
      aria-labelledby="mymodal" aria-hidden="true" [config]="{backdrop: true, ignoreBackdropClick: false}">
      <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            .
            .
            .
    

    子组件.ts

    var1:any;
    var2:any;
    var3:any;
    @ViewChild(mymodal) mymodal;
    
    ... // other code
    
    public show() {
        this.mymodal.show(); //call a modal
    }
    

    父组件

    @ViewChild('mymodal') mymodal: any;
    
    .
    .
    ngOnInit() {
      setTimeout(() => {
      this.mymodal.show(); // Uncaught (in promise): TypeError: Cannot read property 'show' of undefined
      this.mymodal.var1=1;
      this.mymodal.var2=2;
      this.mymodal.var3=3;
    
      }, 5000)
    }
    

    为什么会这样?

    1 回复  |  直到 7 年前
        1
  •  2
  •   zmag    7 年前

    在父组件中引用了错误的变量。

    首先,需要引用模板变量 son modal .

    @ViewChild('modal') modal: any;
    

    mymodal 情态动词 在里面 .

    ngOnInit(){
      setTimeout(()=>{
        this.modal.mymodal.show();
        this.modal.var1=1;
        this.modal.var2=2;
        this.modal.var3=3;
      },5000)
    }
    
    推荐文章