加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 4 – 从子组件调用父方法不起作用

发布时间:2020-12-17 17:51:55 所属栏目:安全 来源:网络整理
导读:我的所有事件发射器都正常工作,除了一个. child.ts: @Component({ ... outputs: ['fileUploaded'] })export class childComponent implements OnInit { ... fileUploaded = new EventEmitterboolean(); ... randomMethod(){ ... this.fileUploaded.emit(tru
我的所有事件发射器都正常工作,除了一个.

child.ts:

@Component({
    ... 
    outputs: ['fileUploaded']
    })

export class childComponent implements OnInit {
  ...
  fileUploaded = new EventEmitter<boolean>();
  ...
  randomMethod(){
     ...
     this.fileUploaded.emit(true);
  }

}

从我将要显示的父组件中调用randomMethod()
parent.ts.它不是在child.html中调用的.

parent.html

...
<child (fileUploaded)="onSubmit($event)"></child>
..

parent.ts

export class parentComponent {
   ...
   theChild = new childComponent;
   submitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('in onSubmit()');
     this.submitted = event;
  }

  functionCallsChild(){
     this.theChild.randomMethod();
     ...
     this.theChild = new childComponent;
  }
}

我的应用程序从不记录“在onSubmit()”中,为什么不调用此方法?我也尝试不在我的最后一行创建一个新的子对象,但这并没有什么区别.

解决方法

您选择的子组件是错误的,您应该像这样使用ViewChild:

parent.html:

<child #theChild (fileUploaded)="onSubmit($event)"></child>

parent.ts:

export class parentComponent {
   ...
   @ViewChild('theChild') theChild;
   submitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('in onSubmit()');
     this.submitted = event;
  }

  functionCallsChild(){
     this.theChild.randomMethod();
     ...
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读