首页 文章

使用Angular2命名动态创建的单选按钮组

提问于
浏览
0

我想通过注意到我对Web开发和Angular2相对较新而对这个问题进行序言 .

我有一个Angular2组件,其功能是使用angular-tree-component库(https://angular2-tree.readme.io)在网页上创建树视图 . 对于树中的每个节点,我已经定义了一个带有单选按钮的popover 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'),它们对每个节点都是唯一的,可用于命名单选按钮 . 但是,我似乎无法获取按钮的名称字段来解析任何表达式并获取树节点提供的数据字段的值 .

如何动态命名单选按钮组以使它们彼此分开?

2 回答

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

    请注意,这只是一个演示如何工作的示例,您必须根据您的要求调整代码

  • 0

    事实证明我在单选按钮的定义中包含了(ngModel)和id字段 . 尽管动态创建的组共享相同的名称,但删除这些字段允许单选按钮按预期运行 .

相关问题