I am trying to trigger a click event on another element but it doesn't work.
My Component:
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>
`
})
When I click on the button I need to trigger (animate) event.
My class:
export class GenerateCar {
@Output() animate = new EventEmitter();
parkingCar() {
this.animate.emit(null)
}
test() {
console.log( 111 )
}
}
I am trying to trigger a click event on another element but it doesn't work.
My Component:
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>
`
})
When I click on the button I need to trigger (animate) event.
My class:
export class GenerateCar {
@Output() animate = new EventEmitter();
parkingCar() {
this.animate.emit(null)
}
test() {
console.log( 111 )
}
}
Share Improve this question edited Aug 16, 2016 at 15:28 after-ephemera 3712 gold badges4 silver badges17 bronze badges asked Feb 15, 2016 at 0:03 Артур ШестериковАртур Шестериков 211 silver badge3 bronze badges1 Answer
Reset to default 3I think set up is not correct or something.
You need to understand the concept of EventEmitter
of Angular2. It allows you to fire custom event
of DOM element
and propagate it to its parent.
I don't understand what you would like to do with EventEmitter
with your example. But I'd like to give you a direction which might help you in your example.
EventEmitter very simple example
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
Note:
(animate) = "test($event)
: It will tell Angular to invoke the ParentComponent's test($event)
method when ChildComponent(car)
fires animate
. The data that we passed to the “next()” method in car
is available in ParentComponent
by passing $event
as an argument to the test()
method.
For further information you can refer to this nice article.
Hope this will help you to go further.