<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'
}
});
}
}
我已经使用这些代码从用户那里获取了值,并进行了一些验证和全部验证。我试图使用patchValue函数用默认值填充下拉列表,但似乎这里存在一些问题。 请帮忙。
答案 0 :(得分:0)
您需要像这样使用[(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>
在此处查看完整答案:https://stackblitz.com/edit/angular-bwujev?file=src%2Fapp%2Fapp.component.html