【问题标题】:How to apply validation in angular 2 dropdown (Model driven Approach)如何在 Angular 2 下拉列表中应用验证(模型驱动方法)
【发布时间】:2017-06-19 10:23:13
【问题描述】:

如果用户单击提交按钮,它不会验证下拉列表。如果用户不选择任何值,我想验证表单,并且在这种情况下表单状态将无效。在我的情况下,如果表单是,我已禁用提交按钮无效,但在这种情况下,它显示的是有效形式。

<div class="form-group col-xs-3">
                <label>User</label>
                <select class="form-control" [(ngModel)]="selectedReferralUser" formControlName="users" required>
                  <option value="-1" selected disabled>--select--</option>
                  <option *ngFor="let user of users" value= {{user.id}}>{{user.name}}</option>
                </select>
              </div>
            </div>

创建订单

export class CreateOrder implements OnInit {
  public createOrderForm: FormGroup;
  public selectedWorkshop = 1;
  public customerId: number;
  public nationalStates: any;
  public selectedState = "New Delhi";
  public workshops: any;
  public selectedPhoneCode = 91;
  public phoneCC: any;
  public loading: boolean = false;
  public enableSubmit = false;
  public userType: any;
  public selectedUserType="";
  public users: any;
  public selectedReferralUser="";


  public ADDRESS_TYPE = {
    PICKUP: "pickup",
    DELIVERY: "delivery"
  };

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private alertService: AlertService,
    private createOrderService: CreateOrderService,
    private weDoShoesCMSService: WeDoShoesCMSService,
    private listItemService: ListItemService,
    private itemDetailsService: ItemDetailsService,
    private googleMapService: GoogleMapService
  ) {
    this.enableSubmit = false;
    this.customerId = Number(localStorage.getItem('customerid'));
    this.nationalStates = this.listNationalState();
    this.phoneCC = this.weDoShoesCMSService.listCountry();
  }


  public searchBox: any;
  public filterDateType: FilterDateType;
  public states: State[];
  public order: Order;
  public showTimePicker: boolean;
  public pickup_date: any;
  public pickSlots: any;
  public selectedPickupSlot = 1;

  ngOnInit() {
    const phoneRegex = `^[2-9]{2}[0-9]{8}$`;
    this.createOrderForm = this.fb.group({
      pickSlots: this.listPickupTimeSlot(),
      pickup_date: ['', Validators.required],
      customer_name: [localStorage.getItem('customerName'), [Validators.required]],
      phone: [Number(localStorage.getItem('customerPhone')), Validators.compose([Validators.required, Validators.pattern(phoneRegex)])],
      addressType: this.initAddressTypeFormGroup(),
      items: this.fb.array([]),
      workshops: this.listWorkshop(),
      userType: this.listUserType(),
      phoneCC: [''],
      users: ['']
    });

    this.addItem();
    this.subscribeAddressTypeChanges();
    this.setAddressType(this.ADDRESS_TYPE.PICKUP);


      }

  initItem() {
    return this.fb.group({
      tax_percentage: [''],
      est_delivery_date: [''],
      est_delivery_time: [''],
      parentServices: [''],
      services: [''],
      brands: [''],
      sizes: [''],
      products: [''],
      discounts: [''],
      is_express_delivery: [''],
      is_packing: [''],
      confirmed: [''],
      coupon: ['']
    });
  }

【问题讨论】:

  • 您如何创建表单对象也显示该代码。你不需要使用NgModel1
  • HTML 中的required 属性 可以进入组件,像这样:users: [-1, Validators.required].

标签: angular validation angular2-forms


【解决方案1】:

您为什么在模型驱动方法中使用ngModel?那是模板驱动的方法。

你可以这样做

private myForm : FormGroup;

let formControl: FormControl;
        formControl = new FormControl('Add your drop down values here', Validators.required);
        this.myForm.addControl('users', formControl);

.html

<select formControlName="users">
            <option value="-1" selected disabled>--select--</option>
            <option *ngFor="let user of users" [value]= {{user.id}}>{{user.name}}</option>
</select>

<alert *ngIf="myForm.controls['users'].invalid" type="danger">Please select value</alert>

【讨论】:

  • 我如何获得选定的值
  • this.myForm.value['users'];
  • 好的,我会做的。但是我将如何验证我的下拉列表,这是我的问题。我可以手动将表单设置为无效状态吗?
  • Validators.required 已经添加到表单控件中,如果您在某处选中myForm.controls['users'].valid,如果没有从下拉列表中选择任何选项,它将显示false。更新了答案。
  • 如果我使用-1,则表明此表单有效。在我的情况下,我不能使用“”,所以有什么办法可以解决这个问题。
猜你喜欢
  • 2017-02-02
  • 2020-11-11
  • 1970-01-01
  • 2017-08-05
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 2017-03-17
相关资源
最近更新 更多