Angular @ViewChild() 错误:预期 2 个参数,但得到 1 个

新手上路,请多包涵

尝试 ViewChild 时出现错误。错误是“未提供 ‘opts’ 的参数。”

@ViewChild 都给出了错误。

 import { Component, OnInit, ElementRef, ViewChild, Output, EventEmitter } from '@angular/core';
import { Ingredient } from 'src/app/shared/ingredient.model';

@Component({
  selector: 'app-shopping-edit',
  templateUrl: './shopping-edit.component.html',
  styleUrls: ['./shopping-edit.component.css']
})
export class ShoppingEditComponent implements OnInit {

@ViewChild('nameInput') nameInputRef: ElementRef;
@ViewChild('amountInput') amountInputRef: ElementRef;
@Output() ingredientAdded = new EventEmitter<Ingredient>();
  constructor() {}

  ngOnInit() {
  }

  onAddItem() {
    const ingName = this.nameInputRef.nativeElement.value;
    const ingAmount = this.amountInputRef.nativeElement.value;
    const newIngredient = new Ingredient(ingName, ingAmount);
    this.ingredientAdded.emit(newIngredient);
  }

}

ts(11,2):错误 TS2554:预期 2 个参数,但得到 1 个。

原文由 stack overflow 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 787
2 个回答

在 Angular 8 中, ViewChild 采用 2 个参数

 @ViewChild(ChildDirective, {static: false}) Component

原文由 Jensen 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 Angular 8.0 中试试这个:

 @ViewChild('result',{static: false}) resultElement: ElementRef;

原文由 SoNu 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进