div元素上的ngModel

时间:2018-12-07 15:18:17

标签: angular ngmodel

这似乎是一个常见的问题,但所有答案仍然无法奏效。我不断收到此错误:

“未捕获(承诺):错误:名称为'gender'的表单控件没有值访问器

这应该是一个下拉菜单,因此您可以过滤性别表。

下面是我的代码:

<div class="dropdown">
   <button class="dropbtn btn btn-outline-primary btn-sm ml-2">Gender
      <i class="fa fa-caret-down"></i>
   </button>
   <div contenteditable="true" 
    class="dropdown-content" 
    name="gender" 
    [(ngModel)]="gender">
       <a value="Male">Male</a>
        a value="Female">Female</a>
   </div>
</div>

下面是我的打字稿

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Customer, GetCustomerDataService } from 'src/app/get-customer-data.service';


@Component({
  selector: 'all-customers',
  templateUrl: './all-customers.component.html',
  styleUrls: ['./all-customers.component.css']
})
export class AllCustomersComponent implements OnInit {
  title = 'CustomerManagementApp';

  gender: string;

  @Output() add = new EventEmitter();
  @Output() edit = new EventEmitter<number>();
  @Output() homeView = new EventEmitter();

  customerArray: Customer[];
  isCustomersView : boolean;

  constructor(
    private getCustomerDataService: GetCustomerDataService
  ) { }

  ngOnInit() {
    this.refresh();
    this.isCustomersView = false;
  }

  refresh() {
    this.getCustomerDataService.retrieveAll().then(
      customerArray => this.customerArray = customerArray
    );
  }

如果我使用“ select”元素,则整个功能都可以正常工作,但是select的css很丑陋且太复杂,因此我改用“ divs”。

在同一件事下面,但是使用“选择”而不是“ div”

<strong>Gender</strong>
      <select class="form-control"
              name="gender"
              [(ngModel)]="gender">  
        <option></option>      
        <option value="male">Male</option>
        <option value="female">Female</option>
      </select>

1 个答案:

答案 0 :(得分:0)

ngDefaultControl添加到您的<div>

<div contenteditable="true" 
    class="dropdown-content" 
    name="gender" 
    [(ngModel)]="gender" ngDefaultControl>
       <a value="Male">Male</a>
        a value="Female">Female</a>
   </div>
</div>

Check this for more details.

Stackblitz for your ref