-1

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

我的组件:

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 )
}

}

4

1 回答 1

3

我认为设置不正确或什么的。

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

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

EventEmitter 非常简单的例子

引导.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);
        }
    }
,
})

汽车.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');
      }
}

工作小插曲


注意: :它会告诉 Angular 在触发(animate) = "test($event)调用 ParentComponent 的test($event)方法。我们传递给“next()”方法的数据可以作为参数传递方法。ChildComponent(car)animatecarParentComponent$eventtest()

有关更多信息,您可以参考这篇不错的文章。

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

于 2016-02-15T06:25:01.233 回答