ng中的引用变量不起作用

时间:2017-06-30 15:49:33

标签: angular2-directives ngfor

我想使用* ngFor

将以下HTML代码转换为Angular代码
<div>Children: <input type="radio" id="1" name="children" [value]="1" [(ngModel)]="this.children"/>1
      <input type="radio" id="2" name="children" [value]="2" [(ngModel)]="this.children"/>2
      <input type="radio" id="3" name="children" [value]="3" [(ngModel)]="this.children"/>3
      You have {{this.children}} children
      </div>

角度代码

<div>Children: <input *ngFor = "let option of selectOptions" type="radio" id=option name="children" [value]=option [(ngModel)]="this.children"/>{{option}}
        You have {{this.children}} children
      </div>

selectOptions在Component的类中定义如下:

selectOptions:Array<number>=[1,2,3]

我可以看到{{option}}

Angular: Identifier 'option' is not defined. The component declaration, template variable declarations, and element references do not contain such a member错误

我也看到id=option name="children" tag start is not closed的错误。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

我使用了这样的代码:

<div>Children: <input *ngFor = "let option of selectOptions" type="radio" id={{option}} name="children" [value]=option />{{option}}
        You have {{this.children}} children
</div>

它适用于这个结果:

enter image description here

生成这个html:

enter image description here

答案 1 :(得分:0)

似乎有一个问题是,一旦输入标签关闭,选项就会超出范围。如果我将* ngFor移动到div,那么我会得到标签。但它们现在垂直显示,而不是水平显示。此代码有效但垂直对齐<div *ngFor = "let option of selectOptions"> <input type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children">{{option}} </div>

对于水平对齐,这很有效。我重复标签,而不是重复div。 label包装输入,因此选项在输入范围内 - <div > <label *ngFor = "let option of this.selectOptions; let ind=index"> <input type="radio" [id]="option" name="children" [value]=option [(ngModel)]="this.children"> {{option}} </label> </div>