-6

I have a opt variable in Typescript

let opt = [{}];

if I want to add multiple children to opt variable to below exsample with for loop

options = [
    { name: "option1", value: 1 },
    { name: "option2", value: 2 }
]

how can I coding

for(i=0; i<=5; i++) {
    ...
}
4

4 Answers 4

1

If you want to add each item in options to opt, then:

let opt = [];

let options = [
    { name: "option1", value: 1 },
    { name: "option2", value: 2 }
]

options.forEach(x => opt.push(x));
Sign up to request clarification or add additional context in comments.

Comments

0

you need to push the value into opt[]

Example:

for(i=0; i<=5; i++) {
    opt.push( { i } );
}

Please make changes as per your requirement for what you want to push into the array.

Comments

0

Try using this

compomnet.html

<select>
  <option *ngFor="let opt of options" [value]="opt.value">{{opt.name}}</option>
</select>

component.ts

options = [
    { name: "option1", value: 1 },
    { name: "option2", value: 2 }
]

Comments

0

If you need to use in select option, you don't need to loop anything in .ts, you can use *ngFor directive in template to display the options.

Try like this:

.html

<select [(ngModel)]="selected">
  <option [value]="null">Select</option>
  <option *ngFor="let opt of options" [value]="opt.value">{{opt.name}}</option>
</select>

<p>selected : {{selected}} </p>

.ts

options = [{ name: "option1", value: 1 }, { name: "option2", value: 2 }];
selected = null;

Working Demo

3 Comments

Don't need to loop anything? I can see the loop in html.
@AliWahab I mean no loop in .ts file, the standard syntax of Angular template using directive *ngFor will do.
Yeah just wanted to correct you if somebody visit this page in future. Well I think the question is not straight. He need to loop through options through .ts, like legacy jQuery style.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.