typescript 如何在angular中调用带有事件的函数?

cwxwcias  于 2023-05-08  发布在  TypeScript
关注(0)|答案(1)|浏览(108)

我有两个组件:picturescamera,其中camera是子节点。
camera中,我有以下类型脚本(当然是简短版本):

@Component({
  selector: 'app-camera',
  templateUrl: './camera.component.html',
  styleUrls: ['./camera.component.scss']
})
export class CameraComponent implements OnInit {
  @Output('onPictureTaken') picture = new EventEmitter<WebcamImage>();
  public webcamImage: WebcamImage;
  pictureTaken(){
    this.picture.emit(this.webcamImage)
}

这个HTML:<button class="actionBtn" (click)="pictureTaken();">Take A Snapshot</button>
pictures中,我有这个代码。 typescript :

export class PicturesComponent implements OnInit {
 // @Output('picture') picture: WebcamImage;
  public pictures: WebcamImage[]
  constructor() {
  }

  ngOnInit(): void {
  }
  onPictureTaken(picture: WebcamImage){
    this.pictures.push(picture)
    console.log("picture taken!!!")
  }
}

这个HTML:

<app-camera ></app-camera>
<table>
    <caption>Photos: </caption>
    <tr (onPictureTaken)="onPictureTaken($any($event))"> </tr>
</table>

无论我怎么尝试,我从来没有达到功能onPictureTaken,我从来没有看到日志‘图片拍摄!!!”
有帮助吗?

toiithl6

toiithl61#

您在错误的地方使用了事件绑定。发射器是为组件app-camera定义的,但您已将其放置在tr标记中。
所以你不用

<app-camera ></app-camera>
<table>
  <caption>Photos: </caption>
  <tr (onPictureTaken)="onPictureTaken($event)"> </tr>
</table>

你需要把它移到你的组件上

<app-camera (onPictureTaken)="onPictureTaken($event)"></app-camera>
<table>
  <caption>Photos: </caption>
  <tr> </tr>
</table>

相关问题