<my-app>
コンポーネントから<app-my-sample>
コンポーネントに、でローカルメソッドを実行する必要があるメソッドのバッチを渡したい<app-my-sample>
。私@ViewChild
はこれを可能にしていました。
@ViewChild()なしで同じになるように、以下のコードのコメントを解除(およびsthを調整)できますか?
@Component({
selector: 'my-app',
template: `
<h3> Angular 6</h3>
Row1: <app-my-sample></app-my-sample><br>
Row2: <app-my-sample [items]='arrayOfActions' #myhook></app-my-sample>
`,
styles: [ 'h3 { font-family: Lato; }' ]
})
export class AppComponent {
name = 'Angular 6';
@ViewChild(MySampleComponent) myhook: MySampleComponent;
arrayOfActions: ActionModel[] = [
// THIS WORKS
{ myAction: () => this.myhook.myFunc1() },
{ myAction: () => this.myhook.myFunc2() },
{ myAction: () => this.myhook.myFunc1() },
// ... BUT I WANT TO PASS THIS BATCH to <app-my-sample> i.e. without @ViewChild
// and have the myFunc1 and myFunc2 methods inside <my-sample-component> called:
// { myAction: () => this.myFunc1() },
// { myAction: () => this.myFunc2() },
// { myAction: () => this.myFunc1() },
]
}
そして<app-my-sample>
:
export interface ActionModel {
myAction: () => void;
}
@Component({
selector: 'app-my-sample',
template: `
<input
*ngFor="let item of items; let i=index"
type="button"
[value]="'BTN-'+i"
(click)="item.myAction()"
>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class MySampleComponent {
@Input() items: ActionModel[] = [
{ myAction: () => this.myFunc1() },
{ myAction: () => this.myFunc2() },
{ myAction: () => this.myFunc1() },
];
myFunc1() {
console.log('Hi from myFunc1 !');
}
myFunc2() {
console.log('Hi from myFunc2 !');
}
}
このstackblitzを参照してください
MySampleComponent
を使用せずにメソッドを実行できるコールバックが必要です@ViewChild
。
MySampleComponent
パラメータとして渡されるようにインターフェイスを更新します。
export interface ActionModel {
myAction: (comp: MySampleComponent) => void;
}
これで、コールバック内でそのパラメーターを使用して、でメソッドを実行できます。 MySampleComponent
arrayOfActions: ActionModel[] = [
{ myAction: (comp: MySampleComponent) => comp.myFunc1() },
{ myAction: (comp: MySampleComponent) => comp.myFunc2() },
{ myAction: (comp: MySampleComponent) => comp.myFunc1() }
];
MySampleComponent
テンプレートを更新して、実行するメソッドを呼び出すようにします。myAction
template: `
<input
*ngFor="let item of items; let i=index"
type="button"
[value]="'BTN-'+i"
(click)="callAction(item)"
>
`
次に、メソッドをMySampleComponent
コンポーネントに追加します
callAction(item: ActionModel) {
item.myAction(this);
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加