【问题标题】:Master detail view in angular2?angular2中的主细节视图?
【发布时间】:2016-10-25 23:26:21
【问题描述】:

编辑:想通了。我将index.html 正文中的所有html 移动到app.component.ts,一切正常。下面的答案是正确的方法。

我的问题是我有一个 ParentComponent,它从服务中读取数据,并将数据发布到侧边栏。当您单击侧栏中的某个项目时,它应该在页面的主要部分中发布有关该父级的详细信息。由于它需要两个不同的模板,我认为解决方案是使用父子关系,其中父是侧边栏,子是细节部分,我将数据传递给子显示。听起来对吗?有没有更好的方法来解决这个问题?我尝试了各种方法,但它们似乎都过时了,因为它使用了不再使用的directives

编辑:另一个问题不一样,因为答案引用了directives,它们在 angular2 的 rc6 版本中被删除。这个问题是rc6后的问题。

编辑 2:添加了一些代码

index.html:

<header>
  <div class="content">This is a header</div>
</header>
<div class="container">
    <div class="sidebar">
      <div class="content">
        <parent-items></parent-items>
      </div>
    </div>
    <div class="main-content">
      <div class="content">
        <my-app>Loading...</my-app>
        <child-cmp [id]="selectedItem.id"></child-cmp>
      </div>
    </div>
    <div class="clearfix"></div>
</div>

子-cmp.ts:

@Component({
  selector: 'child-cmp',
})
export class ChildComponent {
  @Input() set id(n) {
    this.getData(n)
  }
  getData(id: number): void {
     console.log('triggered');
  };
}

父.ts:

@Component({
  moduleId: module.id,
  selector: 'parent-items',
  templateUrl: `<ul class="items">
      <li *ngFor="let item of items"
          (click)="selectedItem = item"
          [class.selected]="item === selectedItem">{{item.name}}</li>
      </ul>`,
})
export class ItemsComponent implements OnInit {
  items: Item[];
  selectedItem: Item;
  constructor(private itemService: ItemService) {};
  getItems(): void {
    this.itemService
        .getItems()
        .then(items => this.items = items);
  }
  ngOnInit(): void {
    this.getItems();
  }
}

【问题讨论】:

标签: angular typescript


【解决方案1】:

听起来很合理。假设父组件有一个children 标识符数组

父模板(侧边栏)

<div *ngFor="let child of children">
    <a (click)="currentChild = child">{{child.name}}</a>
</div>

当一个链接被点击时,它会设置当前的孩子。主要部分将显示当前子项。

父模板(主)

<child-cmp [id]="currentChild.id"></child-cmp>

在 child 中使用 @Input 来接受新的子标识符。设置标识符后,您可以使用新数据填充子项。

子组件

/** Get details from server and populate local variables */
getData(id){
    this.http.get('/api/children/'+id).map(data => data.json()).subscribe(
        data => { this.name = data.name; }
    );
}

/** Executed whenever a new id is set */
@Input() set id(n){ this.getData(n) }

【讨论】:

  • 这是有道理的,但我在实现它时遇到了麻烦。设置 id 似乎不会触发@Input。我在原始帖子中发布了一些代码。
  • 没关系,我想通了。我只需将index.html 正文中的所有html 移动到app.component.ts,因为模板代码不会在index.html 中解析。所以这是我的问题,否则你的方法效果很好。谢谢!
猜你喜欢
  • 2017-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-25
  • 1970-01-01
  • 2013-08-21
  • 1970-01-01
  • 2015-03-07
相关资源
最近更新 更多