首页 > 解决方案 > 知道这个角度主细节实现可能缺少什么吗?

问题描述

Master.component.html 在浏览器加载时显示 2 个任务:

<div class="parent">
  <ol>
    <li
      *ngFor="let task of tasks"
      (click)="onSelect(task)"
      [class.selected]="task === selectedTask"
    >
      {{task.text}} - {{task.done}}
    </li>
  </ol>
  <app-detail [task]="selectedTask"></app-detail>
</div>

When a task in the list above is selected, the onSelect(task) method in the Master.component.ts gets triggered. onSelect(task) 方法当前为空。我希望所选任务显示在 Detail.component.html 中,但目前仅“加载详细信息!” 被展示:

<div *ngIf="task" class="detail">
  <h3>you selected {{task.text}}</h3>
  <table>
      <tr>
        <td>Text:</td>
        <td>{{ task.text }}</td>
      </tr>
      <tr>
        <td>Status:</td>
        <td>{{ task.done }}</td>
      </tr>
    </table>
</div>

{{ task }}

detail loads!

这是 Detail.component.ts:

import { Component, OnInit, Input } from '@angular/core';
import { Task } from '../models/task';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.css']
})
export class DetailComponent implements OnInit {

  @Input() task : Task
  constructor() { }

  ngOnInit() {
  }

}

我创建了这个实现作为我在 youtube 上找到的这个示例的精简版本:https ://www.youtube.com/watch?v=3InW7kyPDCw

知道为什么 Master 中的选定任务没有详细显示吗?

标签: javascriptangular

解决方案


您只需要在选择器上添加*ngIf以便在selectedTask具有值app-detail时加载它,

这是一个例子

<div class="parent">
  <ol>
    <li
      *ngFor="let task of tasks"
      (click)="onSelect(task)"
      [class.selected]="task === selectedTask"
    >
      {{task.text}} - {{task.done}}
    </li>
  </ol>
  <app-detail *ngIf="selectedTask" [task]="selectedTask"></app-detail>
</div>

这是Stackblitz演示


推荐阅读