简体   繁体   English

无法以模板驱动形式在下拉菜单中设置默认值

[英]Can't set the default value in the dropdown in template driven form

<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <form #f="ngForm" (ngSubmit)="onSubmit(f)">
        <div class="form-group" ngModelGroup="userdata" #userdata="ngModelGroup">
          <label for="email" class="form-label">Email Id</label>
          <input name="email" type="email" class="form-control" ngModel email required #email="ngModel"/>
          <span *ngIf="!email.valid && email.touched">Please enter a valid email id<br/></span>
          <label for="subs" class="form-label">Subscription</label>
          <select name="subs" class="form-control" ngModel>
            <option value="basic">Basic</option>
            <option value="advanced">Advanced</option>
            <option value="pro">Pro</option>
          </select>
          <label for="password" class="form-label">Password</label>
          <input type="password" class="form-control" name="password" ngModel required #password="ngModel"/>
          <span *ngIf="!password.valid && password.touched">Please enter a valid password</span>
        </div>
        <button class="btn btn-primary" type="submit">Submit</button>
        <div *ngIf="f.invalid && f.touched">Please enter the corrrect data</div>
      </form>

      <div class="row">
        <div class="col-md-4"></div>
      </div>


    </div>
  </div>
</div>







import { Component,OnInit,ViewChild } from '@angular/core';
import {NgForm} from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
    @ViewChild('f') userForm : NgForm;

    ngOnInit(){
        this.userForm.form.patchValue({
            userdata:{
                subs:'advanced'
            }
        });
    }
}

I have used these code to fetch the value from the user and put some some validations and all. 我已经使用这些代码从用户那里获取值,并进行了一些验证和全部验证。 I tried to fill the dropdown with a default value with the patchValue function.But it seems there is some issue here. 我试图使用patchValue函数用默认值填充下拉列表,但似乎这里存在一些问题。 Please help. 请帮忙。

you need to use [(ngModel)] just like this: 您需要像这样使用[(ngModel)]

 <select class="form-control" id="power"
                required
                [(ngModel)]="ddlDefaultValue" name="power"
                #power="ngModel">
          <option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
  </select> 

check the full answer here: https://stackblitz.com/edit/angular-bwujev?file=src%2Fapp%2Fapp.component.html 在此处检查完整答案: https : //stackblitz.com/edit/angular-bwujev?file=src%2Fapp%2Fapp.component.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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