Angular2锚点对象列表到模板

时间:2017-01-20 23:22:34

标签: angular

简化,假设我的服务组件得到一个锚列表,如:

Url:{href:h1, text:t1} etc

在我的模板中,我有一张桌子,喜欢显示网址文字。

<tr *ngFor="let r of rs">
<td><span>{{r.Url.text}}</span></td>

它会显示[Object Object]我也尝试了r[Url][text]以及所有其他组合无效,我怎样才能获得模板中的值。

抱歉混淆。列表是一个像对象的数组 obj = {f1:string, f2:url}

url ={text:string, href:string}

3 个答案:

答案 0 :(得分:0)

根据提供的信息

在您的组件中,您有类似的内容(网址列表)

public urls: Url[] = [{href:h1, text:t1}, {href:h2, text:t2}]; //get this from service

然后在您看来,以下应该工作

<tr *ngFor="let url of urls">
   <td><span>{{url.text}}</span></td>
</tr>

答案 1 :(得分:0)

好的我相信我知道你想要做什么..你基本上想从对象数组中的一个数组中获取一个嵌套值。嘿,学习过程的所有部分..所以这是一个解决方案..你的服务问题看起来像这样

`   getUrlAnchors() { 
        return [
          {href:'h1', text:'t1'},
          {href:'h2', text:'t2'},
          {href:'h3', text: [
            { href: 'h4', text: 'nestedValue'}
            ] }
      ]
    }` 

所以你必须使用* ngFor ..

迭代一个数组
    //our root app component
import {Component, NgModule, OnInit} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

import {UrlService} from './url-service'

@Component({
  selector: 'my-app',
  template: `
    <div><h2>{{title}}</h2></div>
    <table class="table table-striped">
      <thead>
      <tr>
        <td>
        HREF
        </td>
        <td>
        TEXT
        </td>
      </tr>
      </thead>
    <tbody>
    <tr *ngFor="let r of anchors">
      <td><span>{{ r.href }}</span></td>
      <td *ngIf="r.text.length > 1"><span>{{ r.text }}</span></td>
      <td *ngIf="r.text.length < 2">
        <span *ngFor="let nested of r.text">
          {{ nested.text }}
        </span>
      </td>
    </tr>
    </tbody>
    </table>
  `,
})
export class App implements OnInit {
  title:string;
  public anchors;

  constructor(public urlObj: UrlService) {
    this.title = 'URL Example'
  }

  ngOnInit() {
    this.anchors = this.urlObj.getUrlAnchors();
  }

}

在这里工作Plunker希望这会有所帮助.. plunker

答案 2 :(得分:0)

抱歉提出错误的问题。实际上问题是* ngSwitchCase中的错误。我正在做<a *ngSwitchCase="station" href="{{radio.station.href}}">并且它永远不会得到这个案例并获得* ngSwitchDefault。通过更改*ngSwitchCase="'station'"一切正常。再次感谢您的帮助,我将此答案发布给其他有同样问题的人。