Reputation: 61
I'm trying to make some textboxes appear everytime a user clicks a button. i'm doing this with ngFor. For some reason, the ngFor won't iterate. I've tried using slice to change the array reference, but still, the text boxes won't appear.
Any idea what i'm doing wrong?? Below are the HTML and component codes. Thanks!!!
export class semesterComponent {
subjectsNames = [];
addSubject(subjectName: string) {
if (subjectName) {
this.subjectsNames.push(subjectName);
this.subjectsNames.slice();
console.log(subjectName);
console.log(this.subjectsNames);
}
};
<div class="semester-div">
<ul>
<li ngFor="let subject of subjectsNames">
<span>
<input #subjectName type="text" />
<input id = "subjectGrade" type = "number"/>
<input id = "subjectWeight" type = "number"/>
</span>
</li>
</ul>
<br>
<button (click)="addSubject(subjectName.value)">add</button>
<br>
</div>
Upvotes: 0
Views: 3313
Reputation: 8335
The way you have your controls written subjectName does not exist because the array is empty and therefore the *ngFor
does not render it. Clicking the Add button results in a exception that the value doesn't exist on undefined
where undefined
is really subjectName
.
Moving it outside of the *ngFor
will make things work:
<input #subjectName type="text" />
<ul>
<li *ngFor="let subject of subjectsNames">
<span>
{{subject}}
<input id="subjectGrade" type="number"/>
<input id="subjectWeight" type="number"/>
</span>
</li>
</ul>
I suspect you also want to further bind the data as you iterate over the subject names but that's outside the scope of the question.
Here's a plunker: http://plnkr.co/edit/HVS0QkcLw6oaR4dVzt8p?p=preview
Upvotes: 1
Reputation: 3906
First, you are missing * in *ngFor. Second put out
<input #subjectName type="text" />
from ngFor, should work.
Upvotes: 0
Reputation: 5041
You are missing the * in *ngFor
<li *ngFor="let subject of subjectsNames">
Upvotes: 1