简体   繁体   中英

select and option tags in Angular reactive forms

i'm tryng to create a select with one option for every element in my classes array.

This is my .ts file

@Component({
  selector: 'app-create-deck',
  templateUrl: './create-deck.component.html',
  styleUrls: ['./create-deck.component.scss']
})
export class CreateDeckComponent implements OnInit {

  classes: ['Priest', 'Mage', 'Shaman', 'Rogue', 'Warrior', 'Warlock', 'Druid', 'Paladin']
  createDeckForm: FormGroup;

  constructor() { }

  ngOnInit(){
    this.createDeckForm = new FormGroup({
      'deckName': new FormControl('Meme Deck'),
      'chooseClass': new FormControl('class')
    });
  }
  onSubmit() {
    console.log(this.createDeckForm);
    this.createDeckForm.reset();

is this the right way to loop over the array element?

And this is the .html

<div class="container">
  <div class="row">
    <form [formGroup]="createDeckForm" (ngSubmit)="onSubmit()">
      <label for="deckName">Deck Name</label>
      <input
        type="text"
        id="deckName"
        formControlName="deckName"
        class="form-control"
      />

      <label for="chooseClass">Deck class</label>
      <select id="chooseClass" name="chooseClass">
        <option
            *ngFor="let class of classes"
            [value]="class">
            {{class}}
      </option>
      </select>
    </form>
  </div>
</div>

what i'm doing wrong?

The problem is that you decalre type instead of assign value to your array.

Change this

classes: ['Priest', 'Mage', 'Shaman', 'Rogue', 'Warrior', 'Warlock', 'Druid', 'Paladin']

To this

classes= ['Priest', 'Mage', 'Shaman', 'Rogue', 'Warrior', 'Warlock', 'Druid', 'Paladin']

Or this

classes:[] = ['Priest', 'Mage', 'Shaman', 'Rogue', 'Warrior', 'Warlock', 'Druid', 'Paladin']

A working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM