【问题标题】:Default select option in angular2 not workingangular2中的默认选择选项不起作用
【发布时间】:2016-12-02 07:37:46
【问题描述】:

angular2 开发的一个应用程序,我有不同的食物类别,如果我选择某个类别(例如:沙拉..)并且在该页面中我想添加特定的食物,一个模式会弹出并添加一些字段关于食物的信息,在这些字段中有一个 dropdown-list 具有不同的类别,我想要的是我已经在上面的类别(被选中)将默认显示为选中。

这是category 页面:

top-right 上单击button 将弹出该模式:

我希望默认选择该类别。

这里我做了什么但没有工作:

Add item modal HTML 部分:

<fieldset class="form-group">
    <label for="category">{{'category' | translate}}</label>
    <select
      id="category"
      class="form-control"
      formControlName="select"
      [ngModel]="currentCategory"
    >
      <option [value]="category.id" *ngFor="let category of categories">
        {{category.name}}
      </option>
    </select>
  </fieldset>

这是它的TS 部分:

    export class AddItemModalComponent implements AfterContentInit {
  // @Input() currentCategory: any;
  @Input() isAdvanced:      boolean;

  public currentCategory:       any;
  public  currentCurrency:      string;
  public  itemForm:             FormGroup;
  public  categories:           Category[];
  public  deactivated:          boolean = true;

  private pictureData:          any;
  private categoryId:           string;
  private pictureUploaded:      boolean;
  private isCategoriesLastPage: boolean;
  private pageNumber:           number = 0;


  constructor(
    private router:          UIRouter,
    private formBuilder:     FormBuilder,
    private pageService:     PageService,
    private itemService:     ItemService,
    public  activeModal:     NgbActiveModal,
    private uploadService:   LcUploadService,
    private categoryService: CategoryService
  ) {
    this.categoryId      = this.router.stateService.params['category'];
    this.categoryService.getCategory(this.categoryId).subscribe(
      data => {
        this.currentCategory = data.name;
        console.log(this.currentCategory)
      },
      error => console.log('Could not load category.')
    );
  }

  ngAfterContentInit() {
    this.itemForm        = this.formBuilder.group({
      file:               new FormControl(''),
      item_type:          new FormControl(''),
      internal_reference: new FormControl(''),
      name:               new FormControl('', Validators.required),
      price:              new FormControl('', Validators.required),
      select:             new FormControl('', Validators.required),
      tax:                new FormControl('', Validators.compose([
        Validators.required,
        Validators.pattern(REGEX.ONLY_POSITIVE)
      ])),
      description:        new FormControl('', Validators.compose([
        Validators.minLength(7),
        Validators.maxLength(512)
      ]))
    });

  AddItem(): void {
    let newItem, formValue;
    if (this.itemForm.dirty && this.itemForm.valid) {
      formValue = this.itemForm.value;
      newItem = {
        tax:         formValue.tax,
        name:        formValue.name,
        price:       formValue.price,
        category_id: formValue.select,
        item_type:   formValue.item_type,
        description: formValue.description,
        picture:     this.pictureData.public_id
      };
      this.itemService.addItem(newItem).subscribe(
        (data: any): void => this.activeModal.close(data),
        (error: Response): void => console.log('Could not add item', error.json())
      );
    }
  }
}

它把它带到控制台,但我不知道为什么它不会影响到dropdown-list

这里是打开模态按钮的TS函数:

openAddItemDialog(): void {
    const modalRef: NgbModalRef           = this.modalService.open(
      AddItemModalComponent,
      {size: 'lg'}
    );
    modalRef.componentInstance.category   = this.breadcrumb;
    modalRef.componentInstance.isAdvanced = this.page.advanced;
    modalRef.result.then(
      (result: any): any => {
        if (this.categoryId === result.category.id) {
          this.items.unshift(result);
        }
      },
      (reason: any): void => console.log('Rejected!')
    );
  }

有什么帮助吗?

【问题讨论】:

    标签: html angular drop-down-menu angular-ngmodel


    【解决方案1】:

    只需将默认值分配给currentCategory[selected] 不支持 [ngModel]

    提示:如果你使用[ngValue]而不是[value],你可以分配一个对象

    [ngValue]="category"
    

    分配给[ngModel]="..." 的值必须与分配给[value]="..." or [ngValue]="..." 的值完全匹配。您可以在 {{category.name}]

    中显示您想要的任何值

    如果将[ngValue] 与对象或数组一起使用,则分配给[ngModel] 的值具有相同的属性和相同的值是不够的。它必须是相同的实例

    【讨论】:

    • 但它已经分配了 this.currentCategory = data.name; ,在 data 你会找到类别的对象.. PS :关于 [selected] 我正在测试它不是代码的一部分..
    • 所以currentCategory 包含您要默认选择的category.id
    • 不,它包含类别的名称.. 我想要下拉列表中的这些名称
    • 分配给[ngModel]="..." 的值必须与分配给[value]="..."[ngValue]="..." 的值完全匹配。你可以在&lt;option ...&gt;{{category.name}]&lt;/option&gt;中显示任何你想要的值。
    • 很高兴听到 :) 完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多