2017-04-26 60 views
0

我想通过指出我对Web开发和Angular2相对陌生,来说明这个问题。使用Angular2命名动态创建的单选按钮组

我有一个Angular2组件,其功能是使用角树分量库(https://angular2-tree.readme.io)在网页上创建树视图。对于树中的每个节点,我定义了一个弹出式HTML模板(来自ng2-bootstrap),其中有单选按钮。

由于树的大小可以是任意大小,因此单选按钮是使用树组件HTML中声明的模板在弹出窗口中动态创建的。

我的问题是单选按钮组链接在一起,就好像它们都是单个组。我尝试过几种不同的方式来动态地命名按钮组(最好它们都是单独的组),但似乎没有任何效果。

示例代码:

<div class="testTree"> 
<Tree #tree id="tree1" [nodes]="nodes"> 
    <template #treeNodeTemplate let-node="node" let-index="index"> 
     <span>{{ node.data.name }}</span> 

     <template #popTemplate> 
      <div class="popDiv"> 
       Name: {{node.data.name}}<br> 
       id: {{node.data.id}}<br> 
      </div>   
     <div [innerHtml]="html"></div></template> 

     <template #incTemplate> 
      <div class="popDiv"> 

       <input type="radio" attr.name="node.data.id" 
       value="ab" (change)="foo(node, $event.target.value)"> Button1<br> 

       <input type="radio" attr.name="node.data.id" 
       value="bc" (change)="foo(node, $event.target.value)"> Button2<br> 

       <input type="radio" attr.name="node.data.id" 
       value="cd" (change)="foo(node, $event.target.value)"> Button3<br> 

       <input type="radio" attr.name="node.data.id" 
       value="de" (change)="foo(node, $event.target.value)"> Button4<br><br> 
       <button (click)="bar(node)">ok</button> 

      </div>   
     <div [innerHtml]="html"></div></template> 

     <button class="nodeButton" *ngIf="node.isActive || node.isFocused" 
     [popover]="popTemplate" placement="right" triggers="" popoverTitle="title1" #pop="bs-popover" (click)="pop.toggle()">Details</button> 

     <button class="nodeButton" *ngIf="node.isActive || node.isFocused" 
     [popover]="incTemplate" placement="right" triggers="" popoverTitle="title2" #pop2="bs-popover" (click)="pop2.toggle()">Options</button> 


    </template> 
</Tree> 
</div> 

我试图来命名#incTemplate按钮组在以下几个方面:

name = "node.data.id" 
name = "{{node.data.id}}" 
[attr.name] = "node.data.id" 
attr.name = "{{node.data.id}}" 
attr.name = "node.data.id" 

要查看发生了什么事,我给单选按钮一个id并在angular2类中选择它来记录名称值。该名称可以是空白或文字字符串“node.data.id”。

我会使用ngModel,但由于可能有大量的单选按钮组,我不能让它们使用相同的变量。

每个树节点都有两个变量('id'和'name'),它们对每个节点都是唯一的,可以用来命名单选按钮。但是,我似乎无法获得按钮的名称字段来解析任何表达式并获取树节点提供的数据字段的值。

如何获得动态命名的单选按钮组,以便它们彼此分开?

回答

0

原来我已经包括( ngModel)和单选按钮定义中的id字段。删除这些字段允许单选按钮按预期工作,尽管动态创建的组共享相同的名称。

0

试试这个办法

<div *ngFor="let location of locations"> 
    <input 
    [attr.id]="location" 
    type="radio" 
    name="location" 
    ngModel 
    [value]="location"> 
    <label [attr.for]="location">{{location}}</label> 
</div> 

注意这仅仅是展示它是如何工作的,你必须 根据您的要求调整自己的代码示例