我有一个组件,可以通过不同的动作在父组件中多次使用。我如何将组件单击事件传递给父级。
可以多次使用的我的组件:
import {Component} from 'angular2/core';
@Component({
selector: 'my-card',
template: `<button (click)="onClickMe()">select</button>`
})
export class MyCardComponent {
onClickMe() {
//if my-card in parent component is type 1 do some thing
//if my-card in parent component is type 2 do some thing
}
}
我的父组件html:
<div>
<p>Type 1<p>
<my-card></my-card>
</div>
<div>
<p>Type 2<p>
<my-card></my-card>
</div>
我该怎么办?
@Output() someClickAction = new EventEmitter<void>();
您也可以发送一些数据,只需将void更改为正确的数据类型。
然后在onClickMe()
中仅调用emit
属性上的someClickAction
。
import {Component, EventEmitter, Output} from '@angular/core';
@Component({
selector: 'my-card',
template: `<button (click)="onClickMe()">select</button>`
})
export class MyCardComponent {
@Output() someClickAction = new EventEmitter<void>();
onClickMe() {
this.someClickAction.emit();
}
}
在html中看起来像这样。
<div>
<p>Type 1</p>
<my-card (someClickAction)="someFunction()"></my-card>
</div>
<div>
<p>Type 2</p>
<my-card (someClickAction)="someOtherFunction()"></my-card>
</div>
这里您不会将有关点击的信息发送给孩子,但您将在父级中指定类型,孩子将根据该值来表现。
通过@Input
,您可以为组件指定属性
import {Component, EventEmitter, Input} from '@angular/core';
@Component({
selector: 'my-card',
template: `<button (click)="onClickMe()">select</button>`
})
export class MyCardComponent {
@Input() type: number;
onClickMe() {
if(this.type === 1) {
} else if(this.type === 2) {
}
}
}
HTML中
<div>
<p>Type 1</p>
<my-card [type]="1"></my-card>
</div>
<div>
<p>Type 2</p>
<my-card [type]="2"></my-card>
</div>
您可以详细了解here
使用EventEmitters(https://angular.io/api/core/EventEmitter)。您可以将具有特定值的eventEmitter发射到父组件,在这种情况下,您可以声明卡类型。
儿童:
onClickMe() {
this.myEventEmitter.emit( // any data)
}
父html:
<my-card (myEventEmitter)="anyFunction($event)></my-card>
父项:
anyFunction(args) {
// Do something by type that is declared in args
}
使用输入
import {Component} from 'angular2/core';
@Component({
selector: 'my-card',
template: `<button (click)="onClickMe()">select</button>`
})
@Input() type;
export class MyCardComponent {
onClickMe() {
if (this.type === 1= {
// do something
} else {// do something }
}
}
如果您有更多类型,请使用开关...您的父组件html:
<div>
<p>Type 1<p>
<my-card [type]=1></my-card>
</div>
<div>
<p>Type 2<p>
<my-card [type]=2></my-card>
</div>
使用@Input xyzParameter,您可以将父组件中的值输入到子组件中。以这种方式,您可以控制孩子的行为。
import {Component} from 'angular2/core';
@Component({
selector: 'my-card',
template: `<button (click)="onClickMe()">select</button>`
})
export class MyCardComponent {
@Input() type: number; // that value is taken from the parent´s template
onClickMe() {
//if my-card in parent component is type 1 do some thing
//if my-card in parent component is type 2 do some thing
}
}
我的父组件html:
<div>
<p>Type 1<p>
<my-card [type]="1"></my-card>
</div>
<div>
<p>Type 2<p>
<my-card [type]="2"></my-card>
</div>