角@Output不工作

新手上路,请多包涵

尝试与 @Output 事件发射器进行子级到父级的通信,但在这里不起作用是子组件

import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-emiter',
  templateUrl: './emiter.component.html',
  styleUrls: ['./emiter.component.css']
})
export class EmiterComponent implements OnInit {

@Output() emitor: EventEmitter<any>
  constructor() { this.emitor = new EventEmitter()}

   touchHere(){this.emitor.emit('Should Work');
   console.log('<><><><>',this.emitor) // this comes empty
  }

  ngOnInit() {
  }

}

这是html模板

<p>
<button (click)=" touchHere()" class="btn btn-success btn-block">touch</button>
</p>

touchHere 中的 console.log 它什么也不显示,即使我把它放在父组件中它也什么都不显示

 import { Component , OnInit} from '@angular/core';
// service I use for other stuff//
    import { SenderService } from './sender.service';
// I dont know if I have to import this but did it just in case
    import { EmiterComponent } from './emiter/emiter.component'

@Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      title = 'app';
      user: any;
      touchThis(message: string) {
        console.log('Not working: ${message}');
      }
        constructor(private mySessionService: SenderService) { }
    }

这是 html 模板

<div>
  <app-emiter>(touchHere)='touchThis($event)'</app-emiter>
</div>

原文由 shark6552 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 305
2 个回答

父组件模板:

   <app-emitor (emitor)='touchThis($event)'></app-emiter>

在父模板中,@Output 应该被“调用”,而不是子方法。

另请参阅: https ://angular.io/guide/component-interaction#parent-listens-for-child-event

原文由 Vega 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是我们如何编写具有输出的组件的示例:

 @Component({
  selector: 'single-component',
  template: `<button (click)="liked()">Like it?</button>`
 })
 class SingleComponent {
 @Output() putRingOnIt: EventEmitter<string>;

 constructor() {
 this.putRingOnIt = new EventEmitter();
 }

 liked(): void {
 this.putRingOnIt.emit("oh oh oh");
 }
}

请注意,我们执行了所有三个步骤:1. 指定输出,2. 创建一个我们附加到输出属性 putRingOnIt 的 EventEmitter 和 3. 在调用 liked 时发出一个事件。

如果我们想在父组件中使用这个输出,我们可以这样做:

 @Component({
  selector: 'club',
  template: `
    <div>
      <single-component
        (putRingOnIt)="ringWasPlaced($event)"
        ></single-component>
    </div>`
})
class ClubComponent {
ringWasPlaced(message: string) { console.log(`Put your hands up: ${message}`);
} }
// logged -> "Put your hands up: oh oh oh"

再次注意:

  • putRingOnIt 来自 SingleComponent 的输出
  • ringWasPlaced 是 ClubComponent 上的一个函数
  • $event 包含发出的东西,在本例中是一个字符串

原文由 ValRob 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题