2017-04-04 12 views
0

私はAngularを使い慣れていません。ユーザーがアイテムの行をクリックして詳細行を表示/非表示できるようにしようとしています。私はログエントリのテーブルを持っています。各ログエントリの行には、その下に隠れた行があり、詳細な情報が表示されます。ログエントリ行をクリックすると、詳細行の表示が切り替わります。どのようにして、1つの要素をクリックすると、角度4の別の要素の可視性が切り替わりますか?

私は最初、DOMをクロールして詳細行のスタイルを変更することで、イベントハンドラでこれを完全に解決しました。これは角度に非常に慣用的に感じていなかったので、いくつかの掘削後、私は今、このソリューションを持っている:

関連するHTML:

<tbody> 
    <ng-container *ngFor="let entry of log; let i=index"> 
     <tr class="log-entry" (click)="displayRow[i] = !displayRow[i]"> 
      <td class="datetime">{{entry.datetime}}</td> 
      <td class="actor">{{entry.actor}}</td> 
      <td class="summary">{{entry.summary}}</td> 
     </tr> 
     <tr class="details" [style.display]="displayRow[i] ? 'table-row' : ''"> 
      <td colspan="3"> 
       <pre>{{entry.details}}</pre> 
      </td> 
     </tr> 
    </ng-container> 
</tbody> 

とコード:

import { Component, OnInit } from '@angular/core'; 
import { LogEntry } from '../log'; 
import { LogService } from '../log.service'; 

@Component({ 
    selector: 'app-log', 
    templateUrl: './log.component.html', 
    styleUrls: ['./log.component.styl'] 
}) 
export class LogComponent implements OnInit { 
    log: LogEntry[] 

    // Used by the template to keep track of which rows have details toggled 
    displayRow: boolean[] = [] 

    constructor(private logService: LogService) { } 

    ngOnInit() { 
    this.logService 
     .getLog() 
     .then(this.onLogUpdated) 
     .catch(this.onLogUpdateError) 
    } 

    // Event handlers 

    private onLogUpdated = (log: LogEntry[]) => { 
    console.debug("Redrawing log") 

    this.displayRow = log.map((x) => false) 
    this.log = log 

    console.log(this.displayRow) 
    console.log(this.log) 
    } 

    private onLogUpdateError = (error) => { 
    console.error("Error when trying to get log from log service") 
    console.error(error) 
    } 
} 

あなたは私が見るように詳細行の状態を追跡するためにブール値の配列を維持する必要があります。私はそれが可能な(そして慣用的な)テンプレートの中でこれを達成する必要があるように感じ、私はそれをやる方法を知らない。出来ますか?

答えて

0

さらにAngular 4ガイドを少し読んだところ、私ははるかに良く見える方法を見つけました。

<ng-container *ngFor="let entry of logToday; let i=index"> 
<tr class="log-entry" (click)="toggleRow(details)"> 
    <td class="datetime">{{entry.datetime}}</td> 
    <td class="actor">{{entry.actor}}</td> 
    <td class="summary">{{entry.summary}}</td> 
</tr> 
<tr #details class="details"> 
    <td colspan="3"> 
     <pre>{{entry.details}}</pre> 
    </td> 
</tr> 
</ng-container> 

それはまだコンポーネントコードで定義される関数を使用する必要があります:

// Toggles the visibility of a table row 
toggleRow(row) { 
    if (row.style.display == '') { 
    row.style.display = 'table-row' 
    } 
    else { 
    row.style.display = '' 
    } 
} 

しかし、template reference variableを用いて詳細行をタグ付けし、その変数を使用して行を非表示にする関数を呼び出すことを含みます少なくとも私の以前のアプローチよりもはるかにクリーンです。

注:私のトグル機能は、デフォルトでは詳細行が非表示になっているため、そのように記述されています。

関連する問題