I'm currently working on my angular component's class. I am attempting to gather user input from a form and create an array of words from that input.
The "data" parameter in my submit function is the 'value' attribute of the ngForm. For instance, if the user inputs "hello world," logging data to the console will display this
{word_1: "hello", word_2: "world" }
and typeof keyword indicates it's an object.
The function crashes my app at the first for loop, and I'm struggling to identify the cause. Can anyone assist?
Key points to consider:
- I'm following this method because the number of inputs is unknown beforehand, so I won't know how many keys there will be (word_1 . . . word_N).
- The variable this.inputBoxes doesn't have a value until after onClickSubmit function is called, hence why I'm trying to figure out how to "declare a global array but instantiate it later" in typescript.
This is the function I'm using to extract "hello" and "world," but it keeps crashing my webpage without clear explanation.
component.ts
public inputBoxes: any;
private keys: Array<string>;
onClickSubmit(data) {
let num = parseInt(this.inputBoxes);
this.keys = new Array(num);
for (let idx = 0; idx < num; idx++){
this.keys[idx] = Object.keys(data)[idx];
}
for (let i = 0; i < num; i++){
console.log(data.keys[i]);
}
}
This is my html, although I doubt anything here is causing the issue
component.html
<p>How many words will you be using?</p>
<select (change)="updateInputBoxes($event)">
<option value="">Select Count</option>
<option *ngFor="let num of dropdown_numbers" value={{num}}> {{num}} </option>
</select>
<div *ngIf="inputBoxes">
<form #allWords = "ngForm" (ngSubmit)= "onClickSubmit(allWords.value)" >
<label>Enter the Words for your Crossword</label>
<div *ngFor="let box of createInputBoxes">
<input required ngModel name="word_{{box}}" #word="ngModel" class="form-control">
<div class="alert alert-danger" *ngIf=" word.touched && !word.valid"> Missing word, please insert a word </div>
</div>
<button type="submit" value="submit">Submit</button>
</form>
</div>