【问题标题】:Angular 2 trigger eventAngular 2 触发事件
【发布时间】:2016-02-15 00:03:43
【问题描述】:

我试图在另一个元素上触发点击事件,但它不起作用。

我的组件:

import {Component, Output, EventEmitter} from 'angular2/core';

@Component({
  selector: 'generate-car',
  template: `
    <button [disabled]="!pressed" (click)="parkingCar()"  type="button"  class="parking">Parking Car</button>
    <car *ngFor="#car of cars" [class]="car.type" (animate)="test()">
        <span class="car-number">{{car.id}}</span>
    </car>
`
})

当我点击按钮时,我需要触发(动画)事件。

我的班级:

export class GenerateCar {

@Output() animate = new EventEmitter();

parkingCar() {
    this.animate.emit(null)
}

test() {
    console.log( 111 )
}

}

【问题讨论】:

    标签: javascript events output angular emit


    【解决方案1】:

    我认为设置不正确之类的。

    你需要了解Angular2的EventEmitter的概念。它允许您触发 custom eventDOM element 并将其传播到其父级。

    我不明白你想用EventEmitter 做你的例子。但我想给你一个方向,这可能会对你的例子有所帮助。

    EventEmitter 非常简单的例子

    boot.ts

    @Component({
    selector: 'my-app',
    directives:[Car], 
    template: `
        <div>{{name}} from parent</div><br>
        <car (animate)="test($event)"></car><bR>
            `
    , 
    })
    
    export class BodyContent {  //ParentComponent
    
        name:string='Angular1';
    
          test(arg) {
              console.log('test start');
              //this.animate.subscribe((value) => { this.name = value; });
              this.name=arg;
              console.log(arg);
            }
        }
    ,
    })
    

    car.ts

    export class Car {
          @Output() animate: EventEmitter = new EventEmitter();
    
          setValue()
          {
            console.log('setValue strat');
            this.animate.next('angular2');
    
            // You can also write below line in place of above line
            //this.animate.emit('Angular2');
          }
    }
    

    Working Plunker


    注意: (animate) = "test($event):当ChildComponent(car) 触发animate 时,它将告诉Angular 调用ParentComponent 的test($event) 方法。通过将$event 作为参数传递给test() 方法,我们在car 中传递给“next()”方法的数据在ParentComponent 中可用。

    更多信息可以参考thisnice文章。

    希望这能帮助你走得更远。

    【讨论】:

      猜你喜欢
      • 2016-12-06
      • 1970-01-01
      • 2016-07-28
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多