Angular2 : Parsing data in html tags

2019-08-15 10:35发布

I'm using angular 2 and I'm loading data from a service to my view, specifically to buttons:

my View :

<div id="menuMaisons" class="collapse" *ngFor="#item of items_list">
    <li>
      <div >
         <a href="{{item.href}}" class="{{item.class}}" data-toggle={{'item.toggle'}} data-parent={{'item.parent'}} >
             <span class="titres"> {{item.label}}</span>
         </a>
      </div>
     </li>
</div>

my service is simply parsin this json data :

[

  { "//////////////////SUBMENU MAISON////////////////":""},

  { "id": 1, "href": "#maisonsTemoins" ,"class": "list-group-item", "toggle": "collapse" ,"parent":"#menuMaisons" ,"label":"Maisons Tèmoins" },


  { "id": 2, "href": "" ,"class": "list-group-item", "toggle": " " ,"parent":" " ,"label":"Charger Photo" }


]

the parsing fails and i haven't understood what kind of error is it ; the error :

    EXCEPTION: Error: Uncaught (in promise): Template parse errors: Unexpected closing tag "a" ("                       
 <span class="titres"> {{item.label}}</span>
                                    [ERROR ->]</a>
                                </div>
                            </li>

2条回答
在下西门庆
2楼-- · 2019-08-15 10:43

Although the question was answered properly and accepted but i feel answer is not so much clarified with explanation for questioner few points to be noted here -

  • As of question you can't use {{'item.toggle'}} quotation in between the angular's interpolated syntax, it does't throw any error but angular will treat this as a string and return it back as string you provided in the interpolated expression ({{ }}) . for example -

hello {{name}} {{'name'}}

this.name = "pardeep Jain";

Result is - hello pardeep Jain name

  • While providing dynamic data to predefined elements it's better to use Attribute binding given by angular2. Angular by default uses property binding.To tell Angular explicitly to use attribute binding, we use instead: -[attr.property_name] . for example in the answer-

    [attr.href] , [attr.data-toggle] etc.

  • At the time of property binding to html element better to use elevis operator it does't allow to throw any kind of error and prevent to stop out app it helps when you have done property binding somewhere but due to any reason data is not get properly so angular will throw error in that case better to use elvis operator. for example -

    {{item.abc}} - throw error if item not found

    {{item?.abc}} - prevent error.

查看更多
走好不送
3楼-- · 2019-08-15 11:00
<li> 
      <div >
         <a [attr.href]="item.href" 
            [ngClass]="item.class" 
            [attr.data-toggle]="item.toggle" 
            [attr.data-parent]="item.parent" >
            <span class="titres"> {{item.label}}</span>
         </a>
      </div>
</li>
查看更多
登录 后发表回答