如何将这些代码放到Angular2组件中

时间:2016-06-19 05:15:57

标签: templates angular components repeat

HTML代码:

  <ul class="arc">
    <li class="active"><a href="#">Home</a></li>
    <li class="important"><a href="#">URL1</a></li>
    <li><a href="#">URL2</a></li>
    <li class="other">&nbsp;</li>
  </ul>

Angular2代码:

&#13;
&#13;
    @Component({
      selector: 'arc-list',
      template: `
          <ul class="nav navbar-nav">
          	<li *ngFor="arclink of arclinks"><a href="{{arclink.url}}" title="{{arclink.title}}">
          	{{arclink.description}}</a>
          	</li>
          </ul>
      `
    })
    export class ArcList {
      arclinks = [
        {"url":"#", "description":"Home", "title":"TitleHome", "class":"active"}, 
        {"url":"#", "description":"URL1", "title":"Title1", "class":"important"}, 
        {"url":"#", "description":"URL2", "title":"Title2", "class":""},
        {"url":"", "description":"other", "title":"other", "class":"other"}
      ]
    }
&#13;
&#13;
&#13;

如何编写组件代码以使组件 生成与HTML代码相同的内容

谢谢

1 个答案:

答案 0 :(得分:1)

确保将arclinks设置为您的组件的属性并使用*ngFor="let arclink of arclinks"(注意let关键字):

@Component({
  selector: 'arc-list',
  template: `
      <ul class="nav navbar-nav">
        <li *ngFor="let arclink of arclinks">
          <a href="{{arclink.url}}" title="{{arclink.title}}">{{arclink.description}}</a>
        </li>
      </ul>
  `
})
export class ArcList {
  arclinks = [
    {"url":"#", "description":"Link1", "title":"Title1", "class":"active"}, 
    {"url":"#", "description":"Link1", "title":"Title1", "class":""}, 
    {"url":"#", "description":"Link1", "title":"Title1", "class":""}
  ]
}