Angular2 : Parsing data in html tags

独自空忆成欢 提交于 2019-12-11 11:34:27

问题


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>

回答1:


<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>



回答2:


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.



来源:https://stackoverflow.com/questions/36524135/angular2-parsing-data-in-html-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!