Angular:コンポーネントに関数を渡します。この関数は、ターゲットコンポーネントで実行されると、ローカル(ターゲットコンポーネントへの)メソッドを呼び出す必要があります。

ザギ

<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を参照してください

Reactgular

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]

編集
0

コメントを追加

0

関連記事

Related 関連記事

ホットタグ

アーカイブ