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

Hid*_*ing 5 data-binding eventemitter typescript angular

我的所有事件发射器都正常工作,除了一个.

child.ts:

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

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

}
Run Code Online (Sandbox Code Playgroud)

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

parent.html

...
<child (fileUploaded)="onSubmit($event)"></child>
..
Run Code Online (Sandbox Code Playgroud)

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

小智 8

也许我不清楚为什么你选择这种方法或你需要它,但据我所知,你应该使用EventEmitter从孩子到其父母的.这意味着将触发.emit()shold的事件放在child.html中.尝试这样做,它应该工作:

child.html

<div (click-or-whatever-fires-what-you-want)="randomMethod()"></div>
Run Code Online (Sandbox Code Playgroud)

child.ts:

@Component({
    ... 
    })

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

}
Run Code Online (Sandbox Code Playgroud)

parent.html

...
<child (fileUploaded)="onSubmit($event)"></child>
..
Run Code Online (Sandbox Code Playgroud)

parent.ts

export class parentComponent {
   ...
   submitted = false;
   ...
   onSubmit(event: boolean) { 
     console.log('in onSubmit()');
     this.submitted = event;
  }
}
Run Code Online (Sandbox Code Playgroud)

希望它有所帮助.


eko*_*eko -1

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

父级.html:

<child #theChild (fileUploaded)="onSubmit($event)"></child>
Run Code Online (Sandbox Code Playgroud)

父.ts:

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

  functionCallsChild(){
     this.theChild.randomMethod();
     ...
  }
}
Run Code Online (Sandbox Code Playgroud)