0

と の 2 つのコンポーネントがCommandListComponentありCommandLineComponentます。CommandListComponentテンプレート内で、テキスト文字列のクリック イベントを処理します。

CommandListComponentテンプレート:

<li *ngFor="#command of commandList" class="b-command-list__command"><span (click)="checkCommand(command)" class="b-command-list__text">{{command}}</span></li>

commandlist.component.ts

import {CommandLineComponent} from "./commandline.component";

...

export class CommandListComponent {
    commandLineComponent: any;

    constructor(private _commandLine: CommandLineComponent) {
        this.commandLineComponent = _commandLine;
    }

    checkCommand(command: string): void {
        this.commandLineComponent.add(command);
    }

}

が起動すると、選択したコマンドをa のメソッドにclick渡します。addCommandLineComponent

export class CommandLineComponent {
    commands: string[] = [];

    add(command: string): void {
        if (command) this.commands.push(command);
        console.log(this.commands);
    }
}

そして、i のテンプレート内で、CommandLineComponent*ngFor を使用してコマンドのリストを出力します。

<li *ngFor="#command of commands" class="b-command-textarea__command">{{command}}</li>

commandsしかし、更新されたコマンドと配列を選択しても *ngFor は起動しませんCommandLineComponent。そのため、データバインディングは機能していません。commandsアレイは正常に更新されました:

ここに画像の説明を入力

ご協力ありがとう御座います。

4

1 に答える 1

1

問題は、commandLineComponentコンポーネントを参照する方法です。それらの間に関係がある場合は、ViewChildデコレータを使用できます

class CommandListComponent {
  @ViewChild(CommandLineComponent)
  commandLineComponent: any;
  (...)
}

そうでない場合は、共有サービスを使用して、commandsこれら 2 つのコンポーネント間でリストを共有する必要があります。そんな感じ:

export class CommandService {
  commands:string[] = [];
  commandAdded:Subject<string> = new Subject();

  add(command: string): void {
    if (command) {
      this.commands.push(command);
      this.commandAdded.next(command);
    }
    console.log(this.commands);
  }
}

アプリケーションをブートストラップするときにサービスを定義する必要があり、両方のコンポーネントがそれを注入できます。

class CommandListComponent {
  constructor(private commandService:CommandService) {
  }
}

checkCommand(command: string): void {
    this.commandService.add(command);
}

コンポーネントは次のCommandLineComponentような新しいコマンドの通知を受け、それに応じてビューを更新できます。

class CommandLineComponent {
  constructor(private commandService:CommandService) {
    this.commandService.commandAdded.subscribe(command => {
      // Update the list displayed in the component...
    });
  }
}
于 2016-05-06T12:59:59.470 に答える