コールのみ子法
場合
Child.tsあなたが親と子から通信する必要がある場合は
@Component({
selector: 'child-comp',
template: `
<input type="button" value="click me" (click)="this[funcName]()"> // Here I am calling the function which is assign to a variable
`,
})
export class ChildComp {
funcName: string;
constructor() {
this.funcName = 'dummyFunction'; // assigning function name to variable
}
dummyFunction() {
console.log('do something')
}
}
または
@Component({
selector: 'child-comp',
template: `
<input type="button" value="click me" (click)="funcName()"> // callhere
`,
})
export class ChildComp {
funcName: Fn;
constructor() {
this.funcName = this.dummyFunction.bind(this); // assigning function to variable
}
dummyFunction() {
console.log('do something')
}
}
:
@Component({
selector: 'child-comp',
template: `
<input type="button" value="click me" (click)="funcName()"> // callhere
`,
})
export class ChildComp {
@Input()
funcName: Fn;
constructor() {
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<child-comp [funcName]="dummyFunction"></child-comp>
<p>{{data}}</p>
</div>
`,
})
export class App {
name:string;
data: string;
constructor() {
this.name = 'Angular2';
this.dummyFunction = this.dummyFunction.bind(this);
}
dummyFunction(){ // I want to call this function
data = "function called";
}
}
または使用して出力
import {Component, Output, EventEmitter } from '@angular/core'
@Component({
selector: 'child-comp',
template: `
<input type="button" value="click me" (click)="onClick($event)">
`,
})
export class ChildComp {
@Output() eventName = new EventEmitter();
constructor() {
}
onClick(e) {
// do something here
this.eventName.emit(e);
}
}
親:
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<child-comp (eventName)="dummyFunction()"></child-comp>
<p>{{data}}</p>
</div>
`,
})
export class App {
name:string;
data: string;
constructor() {
this.name = 'Angular2';
}
dummyFunction(){ // I want to call this function
data = "function called";
}
}